Card 08/ 09
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:
class Item {
static int made = 0;
String name;
Item(String name) { this.name = name; made++; }
}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?
| Line | Compiles? | What happens |
|---|---|---|
new Item("pen") | Yes | One object exists; made is 1 |
new Item() | No | Writing a constructor removed the default no-argument one |
Item c = a; | Yes | No new object: a second name for the first one |
Item.made | Yes | Reads the one counter through the class name, which is the clear spelling |
a.made | Yes | Reads 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.
← → move through sections and cards