|
|
Comp201: Principles of Object-Oriented Programming I
|
Problem 11:
Not as written, because bop
is a variable of type IBinaryOp (i.e. staticly
typed as such), which and does not necessarily reference an object of type
AddOp. to which aop
must reference. That is, a variable of the type of the superclas can
always reference an object of the type of any subclass, but a variable of the
type of a particular subclass cannot necessarily reference something of the type
of its superclass. Another way of saying this is that a superset contains its
subsets but not the other way around. The above assignment will cause a compile
time error because the compiler cannot know if the assignment is possible. An
explicit cast is required to supress the compile time error (aop = (AddOp) bop), but may trigger a run-time error if indeed the
instance referred to by bop is not of type AddOp.
Problem 10:
Yes! bop is a variable of type IBinaryOp,
and aop
is defined as referencing an AddOp object, which is
an IBinaryOp.
Problem 9:
No, because aop is a variable of type AddOp ,
and MultIOp is not an AddOp, so
aop cannot reference an instance of
MultOp.
Problem 8: Yes, because aop is a variable of
type AddOp, and thus can reference an instance of the same type.
Problem 7: No, because bop is a
variable of type IBinaryOp , which is not defined as having a
getDescription method. This is true even if bop references an object of
type MultOp. This is because the static typing of bop tells the compiler that it
references an IBinaryOp, not the particular concrete type of the
object it currently references. If we had
MultOp mop = new MultOp(), then mop.getDescription() is perfectly legal.
Problem 6:
It is impossible to tell because it depends on the exact type of the
object instance to which myOp
refers.
Problem 5:
The result is 15 because
bop now refers to an MultOp
instance, whose apply method multiplies its two input values.
Problem 4:
The result is 8 because
bop refers to an
AddOp instance, whose apply method adds its two input values.
Problem 3:
Yes, for the same reasons as the previous exercise!
MultOp is an concrete class and can be instantiated.
MultOp is an IBinaryOp, so bop
can reference it.
Problem 2: Yes! AddOp is an
concrete class and can be instantiated. AddOp is an
IBinaryOp (technically, AddOp
implements the IBinaryOpinterface), so
bop can reference it.
Problem 1:
No, it won't compile. IBinaryOp is an interface and does not specify any actual executable
code, so it cannot be instantiated.
Last Revised Thursday, 03-Jun-2010 09:50:14 CDT
©2006 Stephen Wong and Dung Nguyen