Static Fields and Constants
Use static fields for shared state, constants with static final, and static initializers.
Static Fields and Constants
Static fields belong to the class, not to instances. They are shared across all objects of the class. Constants combine static and final to create class-level immutable values.
Static vs Instance Fields
An instance field has a separate copy per object. A static field has one copy shared by all objects of the class.
class Counter {
private static int totalCount = 0; // shared across all instances
private int instanceId; // unique per instance
Counter() {
totalCount++;
instanceId = totalCount;
}
static int getTotalCount() { return totalCount; }
int getInstanceId() { return instanceId; }
}
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println(Counter.getTotalCount()); // 3
System.out.println(c1.getInstanceId()); // 1
System.out.println(c3.getInstanceId()); // 3All lessons in this course
- Method Overloading Rules
- Varargs Parameters
- Static Fields and Constants
- Utility Classes and Static Factory Methods