Discussion 5: Object-Oriented Programming
Solutions
Download Solution Code download
Exercise 1:
Execution Semantics
Suppose that we execute the following
gameSnippet1()
method:
|
|
|
|
(a)
Draw a memory diagram that depicts the state of the gameSnippet1()
call frame (and all heap objects that can be reached from this call frame by following one or more references) just after line 5 finishes executing. You can fill in any valid value for each Actor
’s power.
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.
(b)
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
.
(c)
When line 7 executes, which method body do we enter? How does Java figure this out?
We enter the body of the
Monster.takeTurn()
method. actor2
references an object with dynamic type Monster
, and dynamic dispatch dictates that this dynamic type is used to determine which "version" of the takeTurn()
method is executed.
Exercise 2:
Compilation Semantics
Now consider the following
What happens when we (try to) run this method? Explain your answer, referencing ideas from lecture.
gameSnippet2()
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 Actor
s (even though actor
references a Player
object), the compiler does not accept this code.