Discussion 5: Object-Oriented Programming
Solutions
Download Solution Code download
Exercise 1:
Compilation Semantics
Consider the following
What happens when we (try to) run this method? Explain your answer, referencing ideas from lecture.
gameSnippet() method:
|
|
|
|
This will not compile! The error is on line 5; the
species() method is only defined for Player, not Actor. The compile-time reference rule says that the static type of a variable is used to determine which methods can be invoked on it. Since the species() method is not available to Actors (even though actor references a Player object), the compiler does not accept this code.
Exercise 2:
Execution Semantics
Suppose that we execute the following
simulate() method:
|
|
|
|
(a)
What is the static type of the variable
actor1? What is the dynamic type of the object that it references?
The static type of
actor1 is Actor, as this is the type that appears in its declaration.
actor1 references an object with dynamic type Player since the Player constructor was invoked on the RHS of the assignment statement to actor1.
(b)
When line 6 executes, which method body do we enter? How does Java figure this out?
We enter the body of the
Player.takeTurn() method. actor1 references an object with dynamic type Player, and dynamic dispatch dictates that this dynamic type is used to determine which "version" of the takeTurn() method is executed.
(c)
Draw a memory diagram that depicts the state of program immediately after entering the takeTurn() method on line 6 (i.e., before any of its local variables have been initialized). You can fill in any valid value for each Actor’s health and power.
The simulate() call frame should be the lowest one depicted on the runtime stack (since we don’t know how we got into this method). To simplify your diagram a bit, you can visualize the GameEngine as an empty rounded rectangle (omitting its fields). Draw all fields of any other objects.