Task 1 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.5 Static and toString — static fields

Lesson

Data shared by the whole class

A normal (instance) field gives each object its own copy. A static field is different: there is one shared copy that belongs to the class, not to any single object. Every object sees the same value. A common use is a counter of how many objects have been made.


Worked example

class Dog {
    static int count;        // one shared counter for all Dogs

    Dog() {
        count = count + 1;   // every new Dog bumps the shared count
    }
}

new Dog();
new Dog();
new Dog();
System.out.println(Dog.count);   // 3

Notice you read it through the class name: Dog.count.


▶ Try it: each new Dog() increases the shared count. Run this, then add or remove new Dog() lines and re-run.



A static field belongs to...


Dog has static int count, increased in the constructor. After three new Dog(), what is Dog.count?


Sort each field by whether it is shared by all objects or is one per object.


True or false?


Type exactly what this program prints.

class Item {
    static int made;
    Item() {
        made = made + 1;
    }
}

public class Main {
    public static void main(String[] args) {
        new Item();
        new Item();
        System.out.println(Item.made);
    }
}