Instance vs. Static Members
Prerequisites: Constructors
An instance field or method belongs to a specific object; a static one belongs to the class itself, shared by every instance.
class Counter {
static int totalCreated = 0; // shared by every Counter
int id; // unique per Counter
Counter() {
totalCreated++;
id = totalCreated;
}
}
Counter a = new Counter();
Counter b = new Counter();
System.out.println(Counter.totalCreated); // 2 — accessed via the class
System.out.println(a.id); // 1
System.out.println(b.id); // 2
main itself is static — the JVM calls it without creating an
instance of the class first, which is also why a static method
can't directly access an instance field.
Common mistakes
- Trying to access an instance field from a
staticmethod without an object to reference it through — there's no implicit object forstaticcode to use.