Static members

Static members define shared data and methods between all instances of the class. They are typically used for constants, factory methods, or utility methods.

The keyword static indicates that the field or method is static. You can also define a static block to initialize static fields.

An instance of a class or child class can directly access static members. In other cases, you must use the class name and the operator .. Or you can use static import, which allows you to use the static members of another class directly.

Static methods have access to the protected and private members of the class instance.

public class Demo {
    // constant field
    public static final int MY_CONST = 100;
    
    // field
    protected static final List<String> sSharedList = new ArrayList<>();
    
    // static block
    static {
        sSharedList.add("str1");
        sSharedList.add("str2");
    }
    
    public static void someMethod(Demo demo, int arg){
        demo.prop = arg; // access to the private field of the class instance
        // ...
    }
    
    private int prop = 10;
}
public void method1(){ // before Java 10 // int val = Integer.MAX_VALUE; var val = Integer.MAX_VALUE; // with class name and dot // ... }
import static java.lang.Integer.*; // ... public void method1(){ var val = MAX_VALUE; // without class name and dot (Integer.) // ... }