Static vs Non-Static Members

Short Answer:
Static members belong to the class, while non-static members belong to the object (instance).

Detailed Explanation:
Static members are shared across all objects of a class and are loaded when the class is loaded. Non-static members are created separately for each object and require an instance to access them.


Key Differences

Static Members Non-Static Members
Belong to the class Belong to the object
Memory allocated once Memory allocated for each object
Accessed using ClassName Accessed using object reference
Can access only static members directly Can access both static and non-static members
Example: main() method Example: instance variables

Example

class Student {

    static String college = "ABC College";   // Static variable
    String name;                             // Non-static variable

    static void showCollege() {              // Static method
        System.out.println(college);
    }

    void showName() {                        // Non-static method
        System.out.println(name);
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Aftab";

        // Accessing static
        Student.showCollege();

        // Accessing non-static
        s1.showName();
    }
}

Important Interview Points

  • Static members are stored in the method area (class area).
  • Non-static members are stored in heap memory.
  • Static methods cannot use this or super.
  • The main() method is static because JVM calls it without creating an object.

0 comments

Leave a comment