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
- Declare the counter inside
Dog.public static int count = 0;goes at the top of the class. Thestatickeyword attaches it to the class, and the= 0sets its starting value, so the counter is 0 before any dog exists. - Increase it in the constructor. After
this.name = name;, addcount++;. The constructor runs once for everynew 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.countsays plainly that the value is shared. Java also lets you writerex.count, which reads the same single field, but it suggests each dog has its own, so avoid it. - The initializer runs once.
= 0on a static field runs when the class is first used, not for each new object. Puttingcount = 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.nameversuscount.thismeans "the object being built", so it is used for the instance field.countneeds nothis, since it doesn't belong to any one dog.
Edge cases and common mistakes
- Forgetting
static. Without it,countbecomes an instance field, every dog starts at 0, andDog.countdoesn't compile, because the class name isn't an object. - Resetting in the constructor. Setting
count = 0orcount = 1there overwrites the shared value instead of adding to it. - Counting in the wrong place. Adding to
countonly inmainFunctioncounts 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.countchanges it for everyone. Assigning from anywhere else can corrupt the count, which is why real programs usually make such a fieldprivateand expose a method to read it.
Key takeaways
- A
staticfield 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
= 0runs once. A constructor runs for every new object, which makes it the right place forcount++. - A static method has no
thisand can't use instance fields directly.
