A static field belongs to the class, not to any one object. Count how many objects were made while each keeps its own clicks.
Java · beginner · 7 min · 25 steps · free
class Counter {
static int created = 0;
int clicks = 0;
Counter() {
created++;
}
void click() {
clicks++;
}
}
public class StaticDemo {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
a.click();
a.click();
b.click();
System.out.println(a.clicks + " " + b.clicks + " " + Counter.created);
}
}main. args holds its command-line arguments (none here). The static variable Counter.created holds 0. There is one copy, shared by the whole class.created is set up once, shared by all Counters.Counter constructor to set up the new object.Object) runs first.int clicks = 0.Counter() has finished, so its variables are gone.a is created on the stack and points to a new Counter on the heap: {clicks: 0}.Counter constructor to set up the new object.Object) runs first.int clicks = 0.Counter() has finished, so its variables are gone.b is created on the stack and points to a new Counter on the heap: {clicks: 0}.click(). It gets its own variables on the stack.click() has finished, so its variables are gone.click(). It gets its own variables on the stack.clicks in the Counter that a points to changes from 1 to 2.click() has finished, so its variables are gone.click(). It gets its own variables on the stack.clicks in the Counter that b points to changes from 0 to 1.click() has finished, so its variables are gone.2 1 2.Answer: No: there is no object. Static code runs without any particular object.
Answer: One per class. It is shared.
← Constructors and this() · Encapsulation: private Fields and Methods →