Sub topic 2
Java Static Methods: Access, Initialization, and Factories
Assume you know how to define classes, create objects with new, use access modifiers, and override methods. A static member belongs to the class, not to a particular object.
What a static method can and cannot access
A static method can directly access static fields and call other static methods. It has no this reference because no object is required to call it. Therefore, it cannot directly access instance fields or instance methods.
public class Person {
private String name;
private static int count;
public Person(String name) {
this.name = name;
count++;
}
public static void printCount() {
System.out.println(count);
// System.out.println(name); // compile error
}
public void printName() {
System.out.println(name);
}
}To use an instance member, a static method needs a specific object reference, such as person.printName().
Constants with `static final`
static final commonly declares a constant: one class-level value that cannot be reassigned after initialization. Constants usually use uppercase names.
public final class Limits {
public static final int MAX_USERS = 100;
}Access it through the class name: Limits.MAX_USERS. A static final reference cannot point to a different object, but the referenced object might still be mutable. Use an immutable type or an unmodifiable wrapper when necessary.
Static blocks and initialization order
A static block initializes complex class-level state. It runs once when the class is initialized, before the class is used.
For one class, static initialization occurs before instance initialization. Each new object runs its instance initialization and constructor again.
Static factory methods
A static factory method creates and returns an object without exposing a public constructor. Its name can describe the input or creation policy.
public final class Temperature {
private final double celsius;
private Temperature(double celsius) {
this.celsius = celsius;
}
public static Temperature ofFahrenheit(double fahrenheit) {
return new Temperature((fahrenheit - 32) * 5 / 9);
}
public double celsius() {
return celsius;
}
}The caller writes Temperature.ofFahrenheit(68). This can be clearer than a constructor and lets the class control validation, caching, or which subtype it returns.
Exercise
Why does a static method need an object reference to read an instance field?
Show answer
An instance field belongs to a particular object, but a static method is called on the class and has no implicit this object.