Polymorphism

Assume the following variable is declared:

SomeClass someObject;

What method is invoked by the following expression?

someObject.someMethod(operand1, operand2, ...);

In an object-oriented language it's hard to say. This is because someObject is only a variable. Presumably it holds a reference to an instance of SomeClass, but not necessarily. Thanks to polymorphism, it could hold an instance of a subclass of SomeClass:

someObject = new SomeSubClass();

Furthermore, someMethod could have been overridden in this subclass. Thanks to dynamic dispatch, it's the override that will be invoked.

This sounds like a bad thing, but it's actually a good thing as it allows programmers to write very abstract code that has many interpretations.

1. A digital media player can play many different types of digital media: audio (wav, wma) and video (mpeg, DVD, blue-ray).

(i) Draw a UML class diagram showing how you would design a digital media player so that new types of digital media could be played without modifying the media player.

2. Olah is a first-person shooter game in which a player moves his avatar through a network of hostile locations. When the avatar enters a location, all of the enemies hiding within attack him. There are different types of enemies, and each has a different style of attacking. Robots crush, aliens zap, and monsters bite.

(i) Draw a UML class diagram showing how you would design Olah so that different types of enemies can be added to the game without requiring changes to existing code.

(ii) Sketch implementations of Location and Robot.

3. There are five types of commands in the Alpha language:

COMMAND ::= CONDITION | ASSIGNMENT | CONDITIONAL | ITERATION | BLOCK

Here is the syntax of each:

CONDITION ::= VARIABLE == VALUE

ASSIGNMENT ::= VARIABLE = VALUE

CONDITIONAL ::= if (CONDITION) COMMAND

ITERATION ::= while(CONDITION) COMMAND

BLOCK ::= {COMMAND; COMMAND; ...; COMMAND;}

A variable contains a value. Values are just objects:

class Variable {
private Object value;
public void setValue(Object newValue) { value = newValue; }
public Object getValue() { return value;
}

The Alpha interpreter can execute Alpha commands:

class Interpreter {
 public void execute(Command cmmd) {...}
}

(i) Draw a UML class diagram showing how you would design the Alpha interpreter so that new commands could be added to the Alpha language without requiring changes to the interpreter. (Hint: represent commands as objects.)

(ii) Show how you would implement the Block class in your design. (Don't worry about parsing.)