static: Shared by the Whole Class

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

What you'll learn

StaticDemo.java

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);
    }
}

Step by step

  1. The program starts in 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.
  2. The class is loaded and its static field created is set up once, shared by all Counters.
  3. Java runs the Counter constructor to set up the new object.
  4. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  5. Line runs: int clicks = 0.
  6. created++ updates the one shared counter: 1.
  7. Counter() has finished, so its variables are gone.
  8. a is created on the stack and points to a new Counter on the heap: {clicks: 0}.
  9. Java runs the Counter constructor to set up the new object.
  10. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  11. Line runs: int clicks = 0.
  12. The second object increments the same counter: 2.
  13. Counter() has finished, so its variables are gone.
  14. b is created on the stack and points to a new Counter on the heap: {clicks: 0}.
  15. Java calls click(). It gets its own variables on the stack.
  16. clicks is an instance field: this changes only a's copy.
  17. click() has finished, so its variables are gone.
  18. Java calls click(). It gets its own variables on the stack.
  19. clicks in the Counter that a points to changes from 1 to 2.
  20. click() has finished, so its variables are gone.
  21. Java calls click(). It gets its own variables on the stack.
  22. clicks in the Counter that b points to changes from 0 to 1.
  23. click() has finished, so its variables are gone.
  24. It prints 2 1 2.
  25. a.clicks = 2, b.clicks = 1, Counter.created = 2. Static data is shared; instance data is per object.

Common mistakes

Best practices

Key takeaways

Check yourself

Can a static method use an instance field directly?

Answer: No: there is no object. Static code runs without any particular object.

How many copies of a static field exist?

Answer: One per class. It is shared.

·

More in Object-Oriented Programming