In Java, a class can contain both static and non-static members.

Static Members:

Static members belong to the class rather than individual objects. They are shared across all instances of the class.

Key Points About Static Members:

  1. Static Variables:

    • Declared with the static keyword.
    • Memory is allocated only once when the class is loaded, and the same value is accessible by all objects.
    • Example:
     class StaticExample {
         static int counter = 0; // static variable
     }
    
  2. Static Methods:

    • Can be called directly using the class name without creating an object.
    • Cannot access non-static variables or methods directly.
    • Example:
     class StaticMethodExample {
         static void display() {
             System.out.println("Static method called");
         }
     }
     StaticMethodExample.display(); // Accessing static method
    
  3. Static Blocks:

    • Used for initializing static variables.
    • Executed once when the class is loaded.
    • Example:
     class StaticBlockExample {
         static int num;
         static {
             num = 10; // Static block initializing static variable
         }
     }
    

Non-Static Members:

Non-static members are tied to specific instances of a class. Each object has its own copy.

Key Points About Non-Static Members:

  1. Instance Variables:

    • Declared without the static keyword.
    • Each object gets its own separate copy of these variables.
    • Example:
     class NonStaticExample {
         int id; // non-static variable
     }
    
  2. Instance Methods:

    • Can access both static and non-static variables.
    • Require an object to be invoked.
    • Example:
     class InstanceMethodExample {
         int id;
         void show() {
             System.out.println("Instance method called: ID is " + id);
         }
     }
     InstanceMethodExample obj = new InstanceMethodExample();
     obj.show(); // Accessing instance method
    

Differences:

Aspect Static Members Non-Static Members
Access Class name Object reference
Memory Shared among all objects Separate for each object
Initialization Initialized at class loading Initialized with object creation
Usage Suitable for shared data (like constants) Suitable for object-specific data

Does this give you a clearer understanding? I can go deeper into concepts or practical use cases if you'd like! 😊