static vs instance members

Core Java · lesson 8 of 42 · 3 min read

Tell class-level state apart from per-object state and choose the right one.

Open this lesson in the learning hub

Key points

  • An instance field belongs to one object. Every new creates a fresh copy.
  • A static field belongs to the class. There is exactly one, shared by every instance.
  • Static methods are called on the class (Math.max(3, 9)) and cannot use this or instance fields.
  • Use static for helpers and constants (static final). Use instance members for anything that describes one object.
  • this means the current object; it is how a constructor tells a field from a parameter with the same name.
  • Mutable static state is shared by every thread in the process, so treat it as a red flag.

Example

public class Main {

    static class Counter {
        static int created = 0;
        private final String name;
        private int clicks = 0;

        Counter(String name) {
            this.name = name;
            created++;
        }

        void click() { clicks++; }

        int clicks() { return clicks; }

        static String summary() { return created + " counters exist"; }
    }

    public static void main(String[] args) {
        Counter left = new Counter("left");
        Counter right = new Counter("right");
        left.click();
        left.click();
        right.click();

        System.out.println("left  -> " + left.clicks() + " clicks");
        System.out.println("right -> " + right.clicks() + " clicks");
        System.out.println("shared static field: " + Counter.created);
        System.out.println("static method on the class: " + Counter.summary());
        System.out.println("Math.max is static too: " + Math.max(3, 9));
    }
}

One copy per class for static, one copy per object for instance.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.