What is a static member, and how does it differ from an instance member in terms of state and lifetime?
A static member belongs to the class rather than to each object made from it. There is one copy of it, and all the objects of that class share it.
public class Main {
public static void main(String[] args) {
System.out.println("id before = " + User.nextId);
User a = new User("Ada");
User b = new User("Grace");
System.out.println("id after = " + User.nextId);
}
}
And here is the class, with one static field and one instance field.
public class User {
static int nextId = 1;
private final int id;
private final String name;
public User(String name) {
this.id = nextId;
nextId = nextId + 1;
this.name = name;
}
}
And how do they differ in terms of state and lifetime?
the thing the static one the instance one
----------------- ------------------------- ----------------------
how many copies one for the whole class one for each object
where it lives the class area the heap
how long it lasts as long as the class is as long as the object
loaded is reachable
So the static field is shared. Every object made from the class sees the same value, and when one of them changes it the others see the change too. And it exists as long as the class is loaded, which is usually for the whole life of the program.
And there is a second difference that matters for the methods. A static method has no object to work on, so it cannot use this and it cannot use the instance fields. It can only use its own arguments and the static fields of the class.
public static Money of(double amount) {
return new Money(Math.round(amount * 100));
}
And there is a third thing worth knowing about, and it is how you call them. You call a static method with the class name, and you call an instance method with the object.
Money m = Money.of(12.5); // the static one
double total = cart.total(); // the instance one
So the rule to remember is this. A static member is one copy that belongs to the class and is shared by every object of it.
The next two questions in this topic explain why static methods cannot use this and when the shared state becomes a problem.