Video in progress
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
thisinside 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:
staticmutable state (such ascreatedabove) is dangerous with many threads and ties tests to each other;- constantly adding to a
staticcollection 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.
Sign up to mark studied questions and save your progress.