Accessing static Fields via Class Name
What you'll learn: The proper, readable way to access static fields using the class name instead of an object reference.
The Preferred Style
You already know how to declare static fields. Now you need to know the right way to access them. While Java technically allows you to access a static field through an instance reference (like myObject.staticField), this is misleading and poor style.
Static fields belong to the class itself, not to any particular object. Therefore, you should always access them using the class name:
ClassName.staticFieldName
Why This Matters
Using the class name makes your code clearer and more honest. When someone reads Counter.totalCount, they immediately understand this is a class-level value shared by all instances. If they see counter1.totalCount, it falsely suggests the field belongs to that specific object.
Example
public class Counter {
public static int totalCount = 0;
public int instanceValue;
}
// Elsewhere in your code:
Counter.totalCount = 10; // ✓ Correct: clear and direct
int x = Counter.totalCount; // ✓ Good style
Counter c = new Counter();
c.totalCount = 10; // ✗ Legal but misleading
int y = c.totalCount; // ✗ Looks like instance field
Both approaches compile, but the class-name version communicates intent clearly. Most IDEs will even warn you when you access static members through an instance.
Analogy
Think of a static field like a school's total enrollment number. You wouldn't ask "What's your school enrollment?" to a single student—you'd ask "What's the school's enrollment?" The data belongs to the institution, not the individual.
Key Takeaway:
Always access static fields using the class name (ClassName.fieldName), not through object references, to clearly communicate that the field is class-level.