Start learning free

LESSON 397 OF 410 · OBJECT-ORIENTED PROGRAMMING

Static Members in Java in Java

Practice

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

    Static Members in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free