Card 08/ 09

ExerciseDifficulty: Intermediate1 min

Practice: Constructors, References and static in Five Lines

One class, five lines: which compile, and how many objects exist afterwards.

Writing a constructor removes the default one, assigning a reference creates no object, and a static field exists once for the class. Using those rules, decide for each of the five lines below whether it compiles and what it does. The class has one constructor taking a name, and one static counter:

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 default 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. Style guides ask for the class name, and javac -Xlint:static warns about this form, because there is only ever one counter.