Start learning free

LESSON 627 OF 671 · OBJECT-ORIENTED PROGRAMMING

Static Members in Java: A Counter Shared by All Objects

Practice Read the full explanation

TL;DR:

A static field is declared with the static keyword. It belongs to the class, so there is one copy shared by every Dog, and you reach it through the class name: Dog.count. Inside the class you can just write count. A static method works the same way and cannot use this.

You start with:

class Dog {
    public String name;
    public Dog(String name) {
        this.name = name;
    }
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Add public static int count = 0; inside Dog.
  • In the constructor, after this.name = name;, add count++;.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.count, not through an object.

class Dog {
    public static int count = 0;

    public String name;
    public Dog(String name) {
        this.name = name;
        count++;
    }
}

class Solution {
    public void mainFunction() {
        Dog rex = new Dog("Rex");
        Dog buddy = new Dog("Buddy");
        System.out.println(Dog.count);
        Dog third = new Dog("Max");
        System.out.println(Dog.count);
        System.out.println(third.name);
        new Dog("Luna");
        System.out.println(Dog.count);
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · OBJECT-ORIENTED PROGRAMMING

    Static Members in Java, explained

    Problem overview

    Normally each object has its own copy of a class's fields. A Dog named Rex and a Dog named Buddy each have their own name. Sometimes a value belongs to the class as a whole instead, such as the number of dogs created so far. A static member does that: there is exactly one copy, shared by every object of the class.

    The lesson starts with a Dog class that has a name and a constructor, and asks you to count the dogs created, with one counter for all of them. The code already in the editor creates Rex and Buddy and prints the counter, creates Max, prints the counter and Max's name, then creates Luna and prints the counter once more. The expected output is:

    2
    3
    Max
    4
    

    Instance members versus static members

    A field declared without static is an instance field: every object carries its own copy. A field declared with static is a class field: it lives with the class, and it exists even before the first object is created. You read it through the class name, Dog.count. Inside the class itself you can write just count.

    The difference shows in a small program with a class Cat that has one of each kind of field:

    public class Main {
        public static void main(String[] args) {
            Cat a = new Cat();
            Cat b = new Cat();
            a.ownCount = 5;
            System.out.println(a.ownCount); // own copy of a
            System.out.println(b.ownCount); // own copy of b
            System.out.println(Cat.total);  // one shared copy
            System.out.println(Cat.describe(Cat.total));
        }
    }
    
    class Cat {
        public static int total = 0;
        public int ownCount = 0;
    
        public Cat() {
            total++;
        }
    
        public static String describe(int n) {
            return "cats: " + n;
        }
    }
    

    It prints:

    5
    0
    2
    cats: 2
    

    Changing a.ownCount doesn't affect b, because each cat has its own. total was increased by both constructors and holds 2, whichever cat you ask.

    Static methods

    A static method works the same way: it belongs to the class, and you call it as Cat.describe(...). Because it isn't called on an object, it has no this and can't use instance fields directly. This version of label does not compile:

    class Cat {
        public String name;
        public static String label() {
            return name;
        }
    }
    

    The compiler reports non-static variable name cannot be referenced from a static context. Which cat's name would it be? The method has no particular cat. A static method may use static fields and its own parameters.

    Step by step

    1. Declare the counter inside Dog. public static int count = 0; goes at the top of the class. The static keyword attaches it to the class, and the = 0 sets its starting value, so the counter is 0 before any dog exists.
    2. Increase it in the constructor. After this.name = name;, add count++;. The constructor runs once for every new Dog(...), whatever the name, so the shared counter goes up by exactly 1 per dog.

    The solution in Java

    class Dog {
        public static int count = 0;
    
        public String name;
        public Dog(String name) {
            this.name = name;
            count++;
        }
    }
    
    class Solution {
        public void mainFunction() {
            Dog rex = new Dog("Rex");
            Dog buddy = new Dog("Buddy");
            System.out.println(Dog.count);
            Dog third = new Dog("Max");
            System.out.println(Dog.count);
            System.out.println(third.name);
            new Dog("Luna");
            System.out.println(Dog.count);
        }
    }
    

    Reading the output against the code: after Rex and Buddy the counter is 2. Max makes it 3, and the program prints it and Max's name. Luna is created without being stored in a variable, which is fine because the constructor still runs, and the counter becomes 4.

    Details worth knowing:

    • Read the counter through the class. Dog.count says plainly that the value is shared. Java also lets you write rex.count, which reads the same single field, but it suggests each dog has its own, so avoid it.
    • The initializer runs once. = 0 on a static field runs when the class is first used, not for each new object. Putting count = 0; inside the constructor would reset the shared counter every time a dog is created.
    • Constructor, not mainFunction. The increment belongs in the constructor so that every creation is counted, wherever it happens.
    • this.name versus count. this means "the object being built", so it is used for the instance field. count needs no this, since it doesn't belong to any one dog.

    Edge cases and common mistakes

    • Forgetting static. Without it, count becomes an instance field, every dog starts at 0, and Dog.count doesn't compile, because the class name isn't an object.
    • Resetting in the constructor. Setting count = 0 or count = 1 there overwrites the shared value instead of adding to it.
    • Counting in the wrong place. Adding to count only in mainFunction counts the dogs that code creates, not the dogs created anywhere else.
    • Using an instance field from a static method. It fails with the compile error shown above.
    • A shared value is shared. Any code that assigns to Dog.count changes it for everyone. Assigning from anywhere else can corrupt the count, which is why real programs usually make such a field private and expose a method to read it.

    Key takeaways

    • A static field has one copy for the whole class, and an instance field has one copy per object.
    • Reach static members through the class name: Dog.count.
    • A static initializer such as = 0 runs once. A constructor runs for every new object, which makes it the right place for count++.
    • A static method has no this and can't use instance fields directly.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free