inheritance and
polymorphism
you are here
4
195
code
candidates:
output:
b.m1();
c.m2();
a.m3();
c.m1();
c.m2();
c.m3();
a.m1();
b.m2();
c.m3();
a2.m1();
a2.m2();
a2.m3();
Aʼs m1, Aʼs m2, Cʼs m3, 6
Bʼs m1, Aʼs m2, Aʼs m3,
Aʼs m1, Bʼs m2, Aʼs m3,
Bʼs m1, Aʼs m2, Cʼs m3, 13
Bʼs m1, Cʼs m2, Aʼs m3,
Bʼs m1, Aʼs m2, Cʼs m3, 6
Aʼs m1, Aʼs m2, Cʼs m3, 13
}
}
}
Set 1 will work.
Set 2 will not compile because of Vampire’s return
type (int).
The Vampire’s frighten() method (B) is not a legal
override OR overload of Monster’s frighten() method.
Changing ONLY the return type is not enough
to make a valid overload, and since an int is not
compatible with a boolean,
the method is not a valid
override. (Remember, if you change ONLY the return
type, it must be to a return type that is compatible
with the superclass version’s return type, and then it’s
an over
ride
.
Sets 3 and 4 will compile, but produce:
arrrgh
breath fire
arrrgh
Remember, class Vampire did not over
ride
class
Monster’s frighten() method. (The frighten() method
in Vampire’s set 4 takes
a byte, not an int.)
BE the Compiler
M
i
x
e
d
M
e
s
s
a
g
e
s
Exercise
Solutions
196
chapter 7
public class Rowboat
extends Boat
{
public
void
rowTheBoat() {
System.out.print(“stroke natasha”);
}
}
public class
Boat
{
private int
length
;
public
void
setLength
(
int len
) {
length = len;
}
public int getLength() {
return length
;
}
public
void
move() {
System.out.print(“
drift
”);
}
}
public class TestBoats {
public static void
main(String[] args){
Boat
b1 = new Boat();
Sailboat b2 = new
Sailboat
();
Rowboat
b3
= new Rowboat();
b2.setLength(32);
b1.
move
();
b3.
move
();
b2
.move();
}
}
public class
Sailboat extends
Boat {
public
void move
() {
System.out.print(“
hoist sail
”);
}
}
drift
drift hoist sail
OUTPUT:
puzzle
answers
this is a new chapter
197
8
interfaces and
abstract classes
Inheritance is just the beginning.
To exploit polymorphism, we need interfaces
(and not the GUI kind). We need to go beyond simple inheritance to a level of flexibility and
extensibility you can get only by designing and coding to interface specifications. Some of the
coolest parts of Java wouldn’t even be possible without interfaces, so even if you don’t design
with them yourself, you still have to use them. But you’ll
want to design with them.
You’ll need
to design with them.
You’ll wonder how you ever lived without them. What’s an interface? It’s
a 100% abstract class. What’s an abstract class? It’s a class that can’t be instantiated. What’s that
good for? You’ll see in just a few moments. But if you think about the end of the last chapter,
and how we used polymorphic arguments so that a single Vet method could take Animal
subclasses of all types, well, that was just scratching the surface. Interfaces are the
poly in
polymorphism. The
ab in abstract. The
caffeine in Java.
Serious
Polymorphism
Make it Stick