What does the static keyword mean in Java when it is applied to a variable, a method, a nested class and an initializer block?
The keyword static means that the thing belongs to the class rather than to an object. Here is what that means in each of the four places you can use it.
On a variable, it means there is exactly one copy for the whole class, no matter how many objects of that class exist. Every object sees the same value, and changing it from one object changes it for all of them.
On a method, it means the method belongs to the class and can be called without having an object. It has no this, and it cannot reach the instance fields of any object.
On a nested class, it means the nested class does not need an instance of the outer class. Without static, an inner class keeps a reference to the outer object, and you cannot create one without an outer object first.
On an initializer block, it means the block runs once, when the class is first used, rather than once for every new object.
public class Main {
static int counter = 0; // one copy for the whole class
int instanceCounter = 0; // one copy for every object
static {
// A static initializer block runs once, when the class is loaded.
System.out.println("the class was loaded once");
}
{
// An instance initializer block runs for every new object.
counter = counter + 1;
}
public static void main(String[] args) {
Main first = new Main();
Main second = new Main();
System.out.println("objects made : " + counter);
System.out.println("first : " + first.instanceCounter);
System.out.println("second : " + second.instanceCounter);
}
}
The next question in this topic lists the rules about what a static member is allowed to touch.