Leepoint Java Reference Notes on the Java language and its standard library.

Static methods

A method that belongs to the class rather than to any object of it.

A static method belongs to the class. You call it on the class, and no object needs to exist:

double r = Math.sqrt(2);
int n = Integer.parseInt("42");

An instance method belongs to an object and is called on one:

String s = "hello";
s.toUpperCase();

Why static methods cannot see instance fields

This is the error everyone meets early:

public class Counter {
    private int count;

    public static void bump() {
        count++;        // won't compile
    }
}

count belongs to an object. A static method is not running on any object, so there is no count to increment: the compiler is asking which one you meant. The same reasoning explains why this is unavailable in a static context.

A static method can use static fields, because those belong to the class too.

When static is right

  • Pure functions of the arguments. Math.max, Integer.parseInt. Nothing about the object matters, because there is no object.
  • Factory methods. List.of(...), Optional.empty(). Named constructors, with the freedom to return a cached instance or a subtype.
  • main. It has to be static, the runtime calls it before any object exists.

When it is not

If the method’s behaviour depends on the state of a thing, it belongs to that thing. A class made entirely of static methods that take the same first parameter is usually a class that wanted to be an object.

Static methods are also awkward to substitute in tests, because there is no reference to swap. That is not an argument against Math.sqrt; it is an argument against making your own service layer static.

Calling them

Call a static method on the class, not on an instance:

Integer.parseInt("42");     // yes
someInteger.parseInt("42"); // compiles, misleading, don't

The second works but suggests the object matters, which it does not.

Static and inheritance

Static methods are not polymorphic. They are resolved at compile time from the declared type, not at run time from the actual object. A static method in a subclass with the same signature hides the parent’s rather than overriding it, and which one runs depends on the reference type. This surprises people; the practical advice is not to do it.