December 21, 2024
An Assignment Exercise
Question:
If the following Smalltalk is evaluated, what is the subsequent state
of frog1 and frog2?
frog1 := Frog new. "Line 1"
frog2 := Frog new. "Line 2"
frog1 position: 7; "Line 3"
colour: Blue.
frog1 := frog2. "Line 4"
frog2 position: 3; "Line 5"
colour: Purple
Variable-reference diagrams (VRD) are useful in helping us understand what is happening. Consider the first two lines of code, which create the two Frog objects. Two VRDs are drawn to depict the initialised state of each object.
frog1 := Frog new.
frog2 := Frog new.
The third line changes the state of the object referenced by frog1. This can be illustrated with another diagram.
frog1 position: 7;
colour: Blue.
The fourth line assigns the object referenced by frog2 to the variable frog1. This is the meaning of
frog1 := frog2
The result is:
So what has happened to the object that frog1 referenced prior to this assignment? Here it is again, just click on the diagram below to find the answer.
The final line changes the state of the object referenced by frog2
frog2 position: 3;
colour: Purple
However, this object has also been assigned to the variable frog1. Consequently, frog1 and frog2 reference the same object. The state of this object can be illustrated with another variable-reference diagram.
The final state of frog1 and frog2 is the same.The value of the colour attribute is Purple and the value of the position attribute is 3. Alternatively, the instance variables colour and position are set to Purple and 3 respectively.
To depict the sending of messages another type of diagram is used.
Next page » Object interaction diagrams
Previous page « Variable reference diagrams
⇑ Up to top of page