Card 08/ 09

ExerciseDifficulty: Intermediate1 min

Five Lines: Which Compile, and What Each One Creates

A class with one constructor taking a name, and one static counter. For each line below, decide whether it compiles and how many objects exist afterwards. Write all five down first.

java
class Item {
    static int made = 0;
    String name;
    Item(String name) { this.name = name; made++; }
}
java
Item a = new Item("pen");
Item b = new Item();
Item c = a;
System.out.println(Item.made);
System.out.println(a.made);
Which of the five compile, and what is true afterwards?
Each line, whether it compiles, and what it does
LineCompiles?What happens
new Item("pen")YesOne object exists; made is 1
new Item()NoWriting a constructor removed the free no-argument one
Item c = a;YesNo new object — a second name for the first one
Item.madeYesReads the one counter through the class name, which is the clear spelling
a.madeYesReads the same one counter through a reference, which compiles and misleads

The last one is worth arguing about. It is legal and it reads as though made belongs to a. Most style guides and most compilers' warnings ask for the class name, because there is only ever one of it.