Video in progress

Junior ☕ Core Java

What are static fields and static methods, and when do you use them?

A static member belongs to the class itself, not to an object: there's one copy of it, and you access it with ClassName.member without creating an object. It's handy for utility methods, constants and factory methods.

📖 Answer

public class Order {
    public static final int MAX_ITEMS = 50;   // a constant
    private static int created = 0;           // one shared by all objects

    private final long id;

    public Order() { id = ++created; }

    public static Order empty() { return new Order(); } // a factory method
}

Order.MAX_ITEMS;
Order.empty();

The rules:

  • there's no this inside a static method, and you can't touch instance fields directly;
  • static methods aren't overridden (a method with the same signature in a subclass "hides" it).

Places to be careful:

  • static mutable state (such as created above) is dangerous with many threads and ties tests to each other;
  • constantly adding to a static collection is the most common cause of memory leaks in prod;
  • putting everything into static utility classes makes the code hard to test. Keep stateful logic in ordinary objects.