Let's explore some different ways in which polymorphism presents itself. Consider the following example of the union design pattern:

/*** An interface that represents an operation on two doubles*/public interface IBinaryOp {double apply( double x, double y); // all interface methods are public and abstract by default}/*** An IBinaryOp that adds two numbers*/public class AddOp implements IBinaryOp {public double apply( double x, double y) {return x+y;}}/*** An IBinaryOp that multiplies two numbers*/public class MultOp implements IBinaryOp {public double apply( double x, double y) {return x*y;}public String getDescription() {return "MultOp is a multiplying function.";}}

Exercise 2.1

Is the following legal code? `IBinaryOp bop = new IBinaryOp();`

## Exercise 2.2

Is the following legal code? `IBinaryOp bop = new AddOp();`

## Exercise 2.3

Given the above declaration and assignment of bop, is the following assignment then possible? `bop = new MultOp();`

## Exercise 2.4

Suppose we have `bop = new AddOp();` , what is the result of `bop.apply(5,3)` ?

## Exercise 2.5

Suppose we now say `bop = new MultOp()`, what is the result of `bop.apply(5,3)` now?

## Exercise 2.6

Suppose we have some variable, called `myOp` of type `IBinaryOp` what is the result of `myOp.apply(5,3)`?

## Exercise 2.7

Suppose we have `bop = new MultOp()`, is it legal to call `bop.getDescription()` ?

## Exercise 2.8

Is the following legal code? `AddOp aop = new AddOp()`

## Exercise 2.9

Given the declaration in the previous exercise, is the following legal? `Aop = new MultiOp()`

## Exercise 2.10

Suppose we have definitions of `aop` and `bop` from above. Is the following legal? That is, can we compile and run the following
statement without error? `bop = aop;`

## Exercise 2.11

Is the converse legal as well? That is, using the above definitions, can we compile and run the following statement? `aop = bop;`

- 2346 reads