A static member belongs to the class itself and is shared by every instance. An instance member belongs to one object and needs that object to exist. There is one copy of a static variable, but every object gets its own copy of each instance variable.
Static variables are initialized once, when the class is first loaded, and you reach static members through the class name, as in Math.max(). A static method has no this, so it cannot use instance fields or call instance methods directly. An instance method can use both kinds.
Use static members for data and behaviour that do not depend on any one object, such as constants and utility methods. Shared static state is harder to test, because every test sees the same copy.
class Example {
static int staticVar = 0; // Class variable
int instanceVar = 0; // Instance variable
static void staticMethod() { // Can't access instance members
// staticVar++; // OK
// instanceVar++; // Compilation error
}
void instanceMethod() { // Can access both
staticVar++;
instanceVar++;
}
}
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓