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;insideDog. - In the constructor, after
this.name = name;, addcount++;. - 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
RexandBuddyand prints the counter; then it createsMax, prints the counter and Max's name, createsLuna, 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);
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
