Card 08/ 09
All 9 cards
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.
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 free 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. Most style guides and most compilers' warnings ask for the class name, because there is only ever one of it.