March 29, 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.

variable reference diagram, frog1, colour Green, position 1 variable reference diagram, frog2, colour Green, position 1

The third line changes the state of the object referenced by frog1. This can be illustrated with another diagram.

frog1 position: 7;
      colour: Blue.

variable reference diagram, frog1, colour Blue, position 7

The fourth line assigns the object referenced by frog2 to the variable frog1. This is the meaning of

frog1 := frog2

The result is:

variable reference diagram, frog1 and frog2, colour Green, position 1

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.

variable reference diagram, unreferenced, colour Blue, position 7

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.

variable reference diagram, frog1 and frog2, colour Purple, position 3

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