Sub topic 3
Java Static Fields and Methods: Utility Classes and Private Constructors
Assume you know classes, objects, access modifiers, and basic inheritance. This chapter focuses on design choices around static.
Utility classes and private constructors
A utility class groups stateless operations. Its methods are usually public static, so callers do not need to create an object. A private constructor prevents accidental construction.
public final class StringUtils {
private StringUtils() {
// Prevent instantiation
}
public static boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
public static void main(String[] args) {
System.out.println(StringUtils.isBlank(" "));
}
}A utility class should not hold mutable global state unless that state is carefully controlled.
Static imports
A static import lets you use a static member without its class name.
import static java.lang.Math.max;
public class Scores {
public static void main(String[] args) {
System.out.println(max(8, 12));
}
}Use static imports sparingly. They can make common constants clearer, but too many can hide where a method comes from.
Static methods are hidden, not overridden
Instance methods are overridden and selected using the object's runtime type. Static methods belong to classes, so a subclass method hides the superclass method.
class Parent {
static String label() { return "parent"; }
}
class Child extends Parent {
static String label() { return "child"; }
}
public class HidingDemo {
public static void main(String[] args) {
Parent value = new Child();
System.out.println(value.label()); // parent
}
}The declared type, Parent, determines the static call.
Static nested classes
A static nested class belongs to its enclosing class but does not need an enclosing object. It can directly access only static members of that class.
class Network {
static class Address {
final String host;
Address(String host) { this.host = host; }
}
}Create one with new Network.Address("localhost").
Static state and thread safety
Shared mutable static state is visible to every caller and every thread. A plain int increment using ++ can lose updates. Use a thread-safe type when concurrent access is possible.
import java.util.concurrent.atomic.AtomicInteger;
final class Ids {
private static final AtomicInteger NEXT = new AtomicInteger();
private Ids() {}
static int next() {
return NEXT.incrementAndGet();
}
}When to use static and when to avoid it
Use static for stateless operations, constants, factories, and genuinely class-wide resources. Avoid it for data that should vary by object, replaceable dependencies, or mutable application state. Static methods cannot be overridden, which limits polymorphism and can make testing harder.
Exercise
Why does a private constructor help a utility class?
Show answer
It prevents callers from creating meaningless instances; callers use the class's static methods instead.