Sub topic 1
Java Static Fields and Methods: Class-Level State and Behavior
Prerequisites
This chapter assumes you can define classes with fields, constructors, and methods. You should also know how to create objects with new, call instance methods, and use basic inheritance and overriding.
Class-level versus object-level members
A class describes objects, but its members can belong to either the class or each object.
- An instance member belongs to one object. Every object has its own copy of an instance field.
- A static member belongs to the class itself. All objects of that class share one copy of a static field.
Use the class name to access static members:
ClassName.memberUse an object reference to access instance members:
object.member| Member kind | Owner | Copies | Typical access |
|---|---|---|---|
| Instance field | One object | One per object | `user.name` |
| Static field | Class | One per class | `User.count` |
| Instance method | One object’s state | Shared method code | `user.login()` |
| Static method | Class | Shared method code | `User.create()` |
Static fields: state shared by all instances
A static field is declared with static. It is useful for information shared by every object, such as a count or a sequence number.
public class Counter {
private static int created = 0;
private final int id;
public Counter() {
created++;
id = created;
}
public int getId() {
return id;
}
public static int getCreated() {
return created;
}
public static void main(String[] args) {
new Counter();
Counter second = new Counter();
System.out.println(second.getId()); // 2
System.out.println(Counter.getCreated()); // 2
}
}Both objects share created, but each object has its own id. The final modifier makes each id assignable only once.
Shared mutable static fields can make code difficult to test and unsafe when multiple threads update them. Prefer immutable values or a thread-safe type when shared state must change.
Static methods: behavior without an object
A static method can be called without creating an object. It can directly use static fields and call other static methods. It has no this reference, so it cannot directly read instance fields or call instance methods.
class Person {
private String name;
private static int count;
public static int getCount() {
return count;
}
// A static method cannot directly use name or this.
}Static methods fit operations that do not depend on one object’s state, such as calculations or class-wide counters.
Exercise
Which member should store a unique name for each object, and which member should count all objects?
Show answer
Use an instance field for the unique name and a static field for the shared count.