ObjectLabeledWithVariableNameDRAFT
When drawing an object in the heap of a stack and heap diagram, the label of the object must be the name of the variable that points to that object (e.g., given code such as Pacman pac = new Pacman()
, the object is labeled as pac
).
In stack and heap diagrams, an object on the heap is labeled with the name of the variable that refers to it
CorrectionHere is what's right.
The connection between a variable and a heap object can change over time. An object and a variable that points to an object are not the same thing! A variable that points to an object at some point in time may be updated so it points to some other object later. When we label a heap object, we want to use a label that does not change.
Moreover, there may be more than one variable that points to the same heap object. How would we pick which variable’s name to use as a label for the object?
Pacman pac = new Pacman();
Pacman alias = pac;
pac = null;
Pacman alias2 = alias;
At the end of the above code, we have two variables, alias
and alias2
, which both point to the same heap object. (Note that by the end of the above code, the original variable doesn’t even point to that object anymore!)
So, in a stack and heap diagram, we label each heap object with its type. In Java, an object cannot ever change its type. Thus, for the above example, we write the word “Pacman” next to the object.
OriginWhere could this misconception come from?
Note that in BlueJ’s object bench, we have to give “names” to objects we place on the object bench. This is probably one reason for this misconception. The BlueJ object bench really does not exist in a Java application. On the Java heap, objects have no names.
Moreover, the Objects First with BlueJ textbook uses UML-style object diagrams where objects can have names (objects are labeled in the form “name : Type”).
SymptomsHow do you know your students might have this misconception?
Students say “allocate variable” instead of “allocate object”.