who inherits what
DtuhemrelDllr"e<Al.,~uesD9ns Q: In a subclass, what if I want to You can design your superclass
methods in such a way that they
Q: SOwe see how a subclass gets use BOTH the superclass version and contain method implementat ions
my overriding subclass version of a that will work for any subclass, even
to Inherlt a superclass method, but method? In other words, I don't want though the subclasses may still need
what If the su perclass wants to use to completely rep/Dee the superclass to 'append' more code . In your subclass
the subclass version of the method1 version, I Just want to add more stuff overriding method, you can call th e
to It. superclass version using the keyword
A.: A superclass won't necessarily super. It's like saying,"first go run the
A:vou can do this! And It's an superclass version. then come back and
know about any of its subclasses . important design feature .Thinkof the finish with my own code ..,"
You might write a class and much word "extends" as meaning ,"1 want
later someone else comes along and to extend the functionality of the
extends it. But even Ifthe superclass su perclass"
creator does know about (and wants
to use) a subclass version of a method, public void roamC)
there's no sort of reverse or backwards super. roam C) ;
inheritance. Think about it, children / / my own roam
Inherit from parents, not the other way
around.
Who gets the Porsche, who gets the porcelah,? Access levels control who sees what, and are crucial
to having well-designed, robust Java cod e. For now we'll
(how to kt'ow whata subclass cat' focus just on public and private. The rules are simple for
Itt"erlt frolM Its superelassJ thos e two:
A subclass inherits members of the --public members are Inherited
superclass. Members include instance
variables and methods, although later in private members are ~ Inherited
this book we'Dlook at other inherited members. A
superclass can choose whether or not it wants a When a subclass inherits a member, it is as if the
subclass to inherit a particular member by the level of
access the particular member is given. subclass defined the -member itself. In the Shape
example, Square inherit ed the rotate () and
There are four access levels that we'D cover in this book. playSound () methods and to the outside world (othe r
Moving from most restrictive to least , the four access code) the Square class simply has a rota te () and
levels are: playSound () method .
The members of a class include the vari ables and
private default protected public methods defined in the class plu s anything in herited
from a superclass.
No-«: get ..O\"C ddails about dc+alAlt and fl"ot.et.ud in 'h4y-W-
Ib (dcrl0't"cnV and .li'fcNli'J< B.
180 chapter 7
When designing with inheritance, Inheritance and polymorphism
are you usit1g or abusi"g? • A subclass extends a superclass.
• A subclass Inherits allpublic Instance
Although some of the reasons behind these rules won't be
revealed until later in this book, for now, simply knowing a variables and methods ofthe superclass, but
few rules will help you build a better inheritance design. does not Inherit the private Instance variables
and methods ofthe superdass,
DO use inheritance when one class is a more specific type
• Inherited methods can be overridden; instance
ofa superclass. Example: WIllow is a more specific type of vartables cannot be overridden (although they
Tree, so Willow extends Tree makes sense.
can be redefined in the subclass, but that's
DO consider inheritance when you have behavior not the same thing, and there's almost never a
need todo it)
(implemented code) that should be shared among • Use the IS-A test toverify thaiyour
multiple classes of the same general type. Example: inheritance hierarchy is valid. If Xextends Y,
Square, Circle, and Triangle all need to rotate and play then X IS-A Ymust make sense.
sound, so putting that functionality in a superclass Shape • The rS-A relationship works In only one
might make sense, and makes for easier maintenance and direction. A Hippo is anAnimal. but not all
extensibility. Be aware, however, that while inheritance is Animals are Hippos.
one of the key features of object-oriented programming, • When a method isoverridden ina subclass,
it's not necessarily the best way to achieve behavior reuse. and that method isInvoked on an instance of
It'll get you started, and often it's the right design choice, the subclass, the overridden version of the
but design panerns will help you see other more subtle method is called. (The lowest one wins.)
and flexible options. !fyou don't know about design • Ifclass B extends A, and C extends B, class
patterns, a good follow-on to this book would be HeadFirst
Design Patterns. B IS-A class A, and class C IS-A class e, and
DO NOT use inheritance just so that you can reuse class C also IS-A class A.
code from another class, if the relationship between the you are here) 181
superclass and subclass violate either of the above two
rules. For example, imagine you wrote special printing
code in the Alarm class and now you need printing code
in the Piano class, so you have Piano extend Alarm so that
Piano inherits the printing code. That makes no sense! A
Piano is rwt a more specific type of Alarm. (So the printing
code should be in a Printer class, that all printable objects
can take advantage of via a HAS-A relationship.)
DO NOT use inheritance if the subclass and superclass
do not pass the IS-A test, Always ask yourself if the subclass
IS-A more specific type of the superclass. Example: Tea IS-
A Beverage makes sense. Beverage IS-ATea does not.
exploiting the power of objects (i) You avoid duplicate
code.
So what does all this
h1herita"ce really buy you? Put common code in one place, and let
the subclasses inherit that code from a
You get a lot of 00 mileage by designing superclass . When you want to change that
with inheritance. You can get rid of duplicate behavior, you have to modify it in only
code by abstracting out the behavior common one place, and everybody else (i.e, all the
to a group of classes, and sticking that code subclasses) see the change.
in a superclass. That way, when you need to • You define a common
protocol for a group of
modify it, you have only one place to update, classes.
and the change is magically reflected in all the
classes that inherit that behavior. Well, there's
no magic involved, but it is pretty simple:
make the change and compile the class
again. That's it. You don't have to touch the
subclassesI
Jmt deliver the newly-ehanged superclass, and
all classes that extend it will automatically use
the new version.
AJava program is nothing but a pile of classes,
so the subclasses don't have to be recompiled
in order to use the new version of the
superclass, As long as the superclass doesn't
break anything for the subclass, everything's
fine. (We'll discuss what the word 'break'
means in this context, later in the book. For
now, think of it as modifying something in
the superclass that the subclass is depending
on, like a particular method's arguments or
return type, or method name, etc.)
182 chapter 7
lt1heritat1ce lets you guarat1tee that Inheritance and polymorphism
all classes grouped ut1der a certaht
supertype have all the Ittethods that And I care because•••
the supertype has:
Because you get to take advantage of
I., other words. you defl"~ a oOttUMO" protocol for a polymorphism.
set ofclasses related through I"herita"ce,
Which matters to me
When you define methods in a superclass, that can be because•••
inherited by subclasses, you're announcing a kind of
protocol to other code that says, "All my subtypes (i.e, Because you get to refer to a subclass
subclasses) can do these things, with these methods object using a reference declared as the
that look like this .;" supertype.
In other words, you establish a contract: And that means to me•••
Class Animal establishes a common protocol for all
Animal subtypes: You get to write really flexible code.
Code that's cleaner (more efficient,
Anlm.1 simpler). Code that's not just easier to
makeNolse() develop, but also much, much easier to
eatO extend, in ways you never imagined at
sleepO
the time you originally wrote your code.
roamO That means you can take that tropical
vacation while your co-workers update
And remember, when we say any AlIima~ we mean the program, and your co-workers might
not even need your source code.
Animal and any classthat extendsfrom Animal Which You'll see how it works on the next page,
We don't know about you, but
again means, any class tha: has Animal SO"TTIeWhere aboue it personally, we find the whole
in the inheritance hierarchy, tropical vacation thing
particu Iarly motivating.
But we're not even at the really cool part yet, because
we saved the best--polymarphism--for last you are here. 183
When you define a supertype for a group of classes,
any subclass 0/that supmype can besubstituted where the
supertype is expected.
Say, what?
Don 't worry. we're nowhere near done explaining it
Two pages from now, you'll be an expert
"When wesay "all the methods' we mean "alilhe Inheritable methods', which
fornow actually means, "all the public methods', although later we'll refine that
defini\Jon a bitmore.
the way polymorphism works
The 3 steps of object
declaration and assignment
To see how polymorphism 12
works, we have to step back ~3~
and look at the way we
normally declare a reference Dog myDog = new Dog();
and create an object...
O Declare a reference
variable
=Dog myDoq new Dog () ; Dog
Tells the JVM to allocate space for a
reference variable. The reference variable
Is,forever, of type Dog. In other words,
a remote control that has buttons to
control a Dog, but not a Cat or a Button
or a Socket.
G Create an object
Dog myDoq = new Dog () ;
Tells the JVM to allocate space for
a new Dog object on the garbage
collectible heap .
Dog object
~ Link the object
~ and the reference
=Dog myDog new Dog () ;
Assigns the new Dog to the refer-
ence variable myDog.ln other words,
program the remote control.
Dog object
Dog
184 chapter 7
inheritance and polymorphism
The important point is that the
reference type AND the object
type are the same.
In this example, both are Dog.
But with polymorphism, the
reference and the object can
be different.
Animal myDog - new ~ () ;
~/'
nest: two .i~e NOT the sd",e t)'Pe. ne
re-ftyel'lu I/ariable t)'Pt is detlarta as APli...aI,
b~t tht objtt+' is tytaud as Pltw D~O.
you are here ~ 185
polymorphism In action
With polymorphism, the reference
type can be a superclass of the
actual object type.
When you declare a reference variable,
any object that passes the IS-Atest for the
declared type of the reference variable
can be assigned to that reference. In
other words , anything that extends the
declared reference variable type can
be assigned to the reference
variable. This lets you do
thing! like make polyrruwphic
arrays.
animals [0] = new Dog(); <- Blot. look ",hdt. 'fOU ~d. to do... ~O" Un fvl:. ANY
s"bclass of A"i...al i.. tnt A..i1'fl41 a.......a'f!
animals [1] = new cat 0 ;
animals [2) = new Wolf() ;
animals [3) = new Hippo () ;
186 chapter 7
Inheritance and polymorphism
But wait! There's more!
You can have polymorphic
arguments and retu!!, types.
If you can declare a reference variable
of a superrype, say,Animal, and assign a
subclass object to it, say, Dog, think of how
that might work when the reference is an
argument to a method...
class Vet {
public void qiveShot(Animal a)
II do horrible things to the Animal at
/ / the other end of the 'a' parameter
a.ma.keNoise();
}
}
class Petowner
public void start ()
Vet v = new VetO;
Dog d = new Dog()i ~
Hippo h = new Hippo(); ~
v. giveShot (d) ; ~ D'1's "",ktNoiUO--1Ai\S
v .giveShot (h) ; ( Itippo's Or\dkeNoiseO l"1AN;
)
)
you are here) 187
exploiting the power of polymorphism
NOW I get itl If I write
my code using polymorphic arguments,
where. r declare the method parameter as a
super-class type, r CM pass in any subclass object at
runtime. Cool. Because that also means r can write my
code, go on vacation, and someone else can add new
subclass types to the program and my methods will
still work ... (the only downside is rm just making life
easier for that idiot Jim).
WIth polytttorphlSttt, you caM write code that doutt't
have to chattge whe.. you 'tttroduce ..ew subclass
types I..tothe progratlt.
Remember that Vet class? If you write that Vet class using
arguments declared as type Animal; your code can handle any
Animal subclass. That means if others want to take advantage of
your Vet class. all they have to do is make sure their new Animal
types extend class Animal. The Vet methods will still work, even
though the Vet class was written without any knowledge of the
new Animal subtypes the Vet will be working on.
Why is polymorphism guaranteed to work this way? Why Is
it always safe to assume that any subclass type will have the
methods you think you're calling on the suoerclass type (the
superclass reference type you're using the dot operator on)?
18a chapter 7
inheritance and polymorphism
D:tihiemreloarH~u?esti0 9n8
Q: Are there any practical limits Q: Can you extend any class? Or Q: Whywould you ever want to
on the levels of subclassing? How is it like class members where if the make a final class? What advantage
deep can you go? class is private you can't inherit it... would there be in preventing a class
from being subclassed?
A.: If you look in the Java API, A.: There's no such thing as a
A: Typically, you won 't make your
you 'll see that most inheritance private class,except in a very special
hierarchies are wide but not deep. classes final. But if you need security
Most are no more than one or two case called an innerclass,that we - the security of knowing that the
levels deep, although there are haven't looked at yet. But there are methods will always work the way
exceptions (especially in the GUI that you wrote them (because they
classes) .You'll come to realize that three things that can prevent a class can't be overridden), a final class
it usually makes more sense to keep from being subclassed. will give you that. A lot of classes in
your inheritance trees shallow, but the Java API are final for that reason.
there isn't a hard limit (well, not one The first is accesscontrol. Even though The String class,for example, is final
that you'd ever run into) .
a class can'tbe marked pr i va t e, a because, well , imagine the havoc if
Q: Hey,Ijust thought of class can be non-public (what you
somebody came along and changed
something... if you don't have get if you don 't declare the class as the way Strings behave!
Kcess to the source code for a class, pub l ic). A non-public class can be
but you want to change the way a subclassed only by classes in the Q: Can you make a method final,
method of that class works, could same package as the class.Classes in
JOu use subclassing to do that? To a different package won't be able to without making the whole class
extend the"bad" class andoverride final?
the method with your own better subclass (or even use, for that matter)
code? A.: If you want to protect a specific
the non-public class.
A.: Yep.That's one cool feature method from being overridden, mark
The second thing that stops a class the method with the fin almodifier.
of 00, and sometimes it savesyou from being subclassed is the keyword
modifier final. A final class means Mark the whole class as final if you
from having to rewrite the class that it's the end of the inheritance want to guarantee that none of the
from scratch, or track down the line. Nobody, ever, can extend a final
programmer who hid the source code. class. methods in that class will ever be
overridden .
The third issue is that if a class has
only p r i va te constructors (we'll
look at constructors in chapter 9), it
can't be subclassed.
you are here r 189
Keepl.,g the co"tract: rules for overriding
When you override a method from a supercIass, you 're agreeing to Appliance
fulfill the contract. The contract that says. for example, ~I take no boolean bJmOnO
arguments and I return a boolean ." In other words, the arguments
and return types of your overriding method must look to the outside
world exactly like the overridden method in the superclass.
The methods are the contract. boolean bJmOffO
If polymorphism is going to work. the Toaster's version of the
overridden method from Appliance has to work at runtime.
Remember. the compiler looks at the reference type to decide
whether you can call a particular method on that reference. Wilh
an Appliance reference to a Toaster, the compiler cares only if class
Appliance has the method you 're invoking on an Appliance reference . Toaster
But at runtime, thejVM looks not at the reference type (Appliance) but
at the actual Toaster object on the heap. So if the compiler has already ~ boolean tumOn(~lleveD
approved the method call, the only way it can work is if the overriding "This \~ 1'./01 6"
method has the same arguments and return types. Otherwise. '1t:Y""'\dt~
someone with an Appliance reference will call turn On 0 as a no- o. \:. t.hb6~"e \)Ie
arg method, even though there's a version in Toaster that takes an ta" 61\
int. Which one is called at runtime? The one in Appliance. In other ~\WI'.~~....e-t.n06I. .
O~~I
words, the turnOn{int level) m.etJwd in Toaster is not an override.' ThIs j! .t,i:.ua/ly .a Je5d1
oolvlee"rrLROIDAED. I b· i .L an
""l; "()l:.
Arguments must be the same, and return
types must be compatible.
The contract of superclass defines how other code can use a method. Appliance
Whatever the superclass takes as an argument. the subclass over-
riding the method must use that same argument. And whatever the pUblic boolean tumOnO
superclass declares as a retum type. the overriding method must de- public boolean tumOnO
clare either the same type. or a subclass type . Remember, a subclass
object is guaranteed to be able to do anything its superclass declares.
so iI's safe to retum a subclass where the superclass Is expected.
• The method can't be less accessible.
That means the access level must be the same, or friendlier. That Toaster
means you can't, for example, override a public method and make
It private. What a shock that would be to the code invoking what It
thinks (at compile time) is a public method. If suddenly at runtime
the JVM slammed the door shut because the overriding version
called at runtime Is prlvatel
So far we've leamed about two access levels : private and public . privata boolean bJmOnO
The other two are In the deployment chapter (Release your Code)
and appendix B. There's also another rule about overriding related \
to exception handling , but we'll walt until the chapter on exceptions
(Risky Behavior) to cover thaI.
190 chapter 7
inheritance and polymorphism
Overloading a tttethod An overloaded method is
~
just a dii±erent method that
Method overloading is nothing more than having happens to have the sane
two methods with the same name but different
argument lists. Period. There's no polymorphism method name, It has nothing
involved with overloaded methods!
to do with inheritance and
Overloading lets you make multiple versions pol)'Illorphism. An overloaded
of a method, with different argument lists, for method is NoT the sane as
convenience to the callers. For example, if you an overridden method.
have a method that takes only an int, the calling
code has to convert, say, a double into an int
before calling your method. But if you overloaded
the method with another version that takes a
double, then you've made things easier for the
caller. You'll see more of this when we look into
constructors in the object lifecyc1e chapter.
Since an overloading method isn't trying to
fulfill the polymorphism contract defined by its
superc1ass, overloaded methods have much more
flexibility.
• The return types can be Legal examples of method
different. overloading:
You're free to change the return types in public class Overloads
overloaded methods, as long as the argument lists String uniqueID;
are different.
• You can't change ONLY the public int addNums(int a, int b) (
return type. return a + b;
If only the return type is different, it's not a public double addNums(double a, double b) (
valid overload-the compiler will assume
you're trying to override the method. And even return a + b;
that won 't be legal unless the return type is
a subtype of the return type declared in the public void setUniqueID(String theID) (
superclass. To overload a method, you MUST II lots of validation code, and then:
change the argument list, although you can uniqueID = theID;
change the return type to anything.
• You can vary the access public void setUniqueID(int ssNumber)
levels in any direction. String numString = "" + ssNumber;
setUniqueID{numString);
You're free to overload a method with a method
that's more restrictive. It doesn't matter, since the
new method isn't obligated to fulfill the contract of
the overloaded method.
you are here ~ 191
exercise: Mixed Messages Mix~d A short Java program is listed below . One block of
the program is missing! Your challenge is to match
the prograttt: MessagES the candidate block of code (on the left), with the
output that YOU'd see if the block were Inserted.
a ~ 6i~56 Not all the lines of output wIll be used, and some of
b ~ Si 11 the lines of output might be used more than once .
Draw lines connecting the candidate blocks of
a ~ 5i 65 code with their matching command-line output.
class A { class C extends B {
int ivar ;; 7; void m3() {
void ml() ( system.out.print(UC's nU, "+(ivar + 6»;
System.out.print("A'S mIt ");
public class Mixed2 {
}
public static void main(String [I args) {
void m2 () {
System.out.print("A'S m2, "); A a "" new A(); cattdldate code
B b ;; new B(); ~ goes here
}
C c = new e();
void m3() (
System.out.print("A's m3, U); A a2 = new C ( ) ;
class B extends A { ' - - - - - - - - - -I (three IIttes)
void ml (I (
System.out.print(UB'S ml, U); }
}
}
code b.ml (); output:
candidates:
}c.m2(); A's ml, A's m2, C's m3, 6
B's ml, A's m2, A's m3,
a.m3 (); A's ml, B's rn2, A's m3,
B's ml, A's m2, C's m3, 13
}c .ml ( ); B's ml, C's m2 t A's m3,
B's m1, A's rn2, C's m3, 6
c.m2();
c.m3(); A's m1, A's rn2, C's mJ, 13
}a.ml()i
b.rn2();
c.m3();
a2.ml(); }
a2 .m2 ( ) i
a2 .m3 ( ) ;
192 chapter 7
inheritance and polymorphism
BE the Ct»mriler
"Which ofthe A-B pai.rS ofmethods listed on the right, if
inserted into the classes on the left. would compile and
produce the output shown? (The AltIethod inSerted into
class Monster, the B JIlethod inserted into class VlUtlpil'e.)
public class MonsterTestDrive { 1 boolean frighten(int d) {
public static void maio(String (I args) { System.out.println("arrrgh U);
e return true;
=Monster (J rna new Monster(3J:
}
ma[OI new Vampire();
marl) new Dragon(): boolean frighten(int x)
ma[2J new Monster(): System.out.println("& bite?");
for(iot x = 0: x < 3; X++) { return false;
ma[xJ.frighten(x); }
} 2e boolean frighten(int x) {
} System.out.println(Uarrrgh");
} 4) return true;
class Monster { }
} iot frighten(int f) {
System.out.println(Ua bite?");
return 1:
}
class Vampire extends Monster ( 3 boolean frighten(int x) {
System.out.println("arrrgh"):
} e return false;
class Dragon extends Monster { }
boolean frighten(int degree)
System. out. println ("breath fire"); boolean scare(int x) {
return true; System.out.println("a bite?"):
return true;
}
}
4e boolean frighten(int z) {
System.out.println("arrrgh")i
o return true;
}
boolean frighten(byte b) {
System.out.println("a bite?H);
return true;
you are here ~ 193
puzzle: Pool Puzzle
Pool Puzzle
Your Job is to take code snippets from the pool and place them into
the blank lines In the code .You may use the same snippet more
than once, and you might not need to use all the snippets.Your
goal Is to make a set of classes that will compile and run together
as a program. Don't be fooled - this one's harder than It looks.
public class Rowboat { public class TestBoats {
public rowTheBoat() { _____ _ _ _ _ main(String( I args){
Syatem.out.print(nstroke natashaW)i ______ bI = new Boat();
Sailboat b2 = new ();
} Rowboat _ new Rowboat ( ) ;
public class b2.setLength(32);
private int
____ void _ ){ bl. ( ) i
__ b3. ()i
length:: len; _ _ _ .move();
} }
public int getLength() {
} move() { public class Boat {
public () {
public System. out. print ( u
") ;
}
System. ou t . print (" H) ; }
}
}
OUTPUT: drift drift hoist sail
194 chapter 7
code inheritance and polymorphism
catldldates:
Set 1 will work.
Mixed
MessagES Set 2 will not compile becauseof Vampire's retum
type (Int).
The Vampire's frightenO method (B) is not a legal
override OR overload of Monster'sfrightenO method.
Changing ONLYthe retum 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 retum
type, it must be to a retum type that Is compatible
with the superclass version's retum type, and then ifs
an override.
Sets 3 and 4 will compile, but produce:
arrrqh
breath fire
arrrgh
Remember, class Vampire did not override class
Monster's frightenO method. (The frightenO method
in Vampire's set 4 takes a byte, not an lnr.)
A's m2, C's m3, 6
A's mz , A'9 m3,
B'B m2, A's m3,
A's mz , C's nU, 13
B's ml, C's m2, A's m3,
B's ml, A's 11\2, C's m3, 6
A'8 ml, A'S m2, e's m3, 13
you are he re ~ 195
puzzle answers pUblic class Rowboat extends Boat
public void rowTheBoat() {
• System.out.print("stroke natasha")1
public class Boat {
private int length
public void setLength ( int len ) {
length = lenl
public int getLength()
return length 1
pub.l.Lc void move ( )
System. out. print( "drift") 1
public class TestBoats {
public static void main(String[ l args) {
Boat bl = new Boat()l
Sailboat b2 = new Sailboat ( ) 1
Rowboat b3 = new Rowboat()1
b2.setLength(32)1
bl.mOVe() 1
b3.mOVe() 1
b2 .move() 1
pubLi.c class Sailboat extends Boat {
public void mover i {
System.out.print( "hoist sail •• ) 1
OUTPUT: drift drift hoist sail
196 chapter 7
8 interfaces and abstract classes
Serious Polymorphism
Inheritance is just the beginning. 4O
designing with inheritance Animal
Did we forget about something picture
when we designed this? food
hunger
4HE
interfaces and polymorphism
We know we can say:
Wolf aWolf = new Wolf();
aWolf
A Wolf reference to a Wolf object
Wolf object. Wolf
These two are the same type.
And we know we can say:
Animal aHippo = new Hippo();
Animal reference to aHippo Hippo object
a Hippo object. Animal
These two are NOT the same type.
But here’s where it gets weird:
Animal anim = new Animal();
Animal reference to anim ?
an Animal object. Animal
Animal object
These two are the same type, but...
what the heck does an Animal object look like?
you are here4 199
when objects go bad
What does a new Animal() object
look like?
scary objects
What are the instance variable values?
Some classes just should not be
instantiated!
)T
interfaces and polymorphism
The compiler won’t let you instantiate
an abstract class
!N
abstract and concrete classes
Abstract vs. Concrete abstract
!
Abstract methods interfaces and polymorphism
"ESIDES
you must implement abstract methods
You MUST implement all abstract methods
I have wonderful news,
mother. Joe finally implemented
all his abstract methods! Now
everything is working just the
way we planned...
Implementing an abstract
method is just like
overriding a method.
!BSTRACT
interfaces and polymorphism
Sharpen your pencil !BSTRACT
polymorphism examples
Polymorphism in action
,ET S
interfaces and polymorphism
Uh-oh, now we need to keep Cats, too.
7E
the ultimate superclass: Object
What about non-Animals? Why not make
a class generic enough to take anything?
9OU
interfaces and polymorphism
So what’s in this ultra-super-megaclass Object?
)F
Object and abstract classes
DtuhemrebareQnuo estions Q: /+
interfaces and polymorphism
Using polymorphic references of type Object has a price...
"EFORE
When a Dog loses its Dogness I don’t know what you’re
talking about. Sit? Stay?
When a Dog won’t act like a Dog bark? Hmmmm... I don’t
4HE
interfaces and polymorphism
Objects don’t bark.
3O
objects are Objects
He treats me like an
Object. But I can do so
much more...if only he’d see
me for what I really am.
Get in touch with your inner Object.
!N
‘Polymorphism’ means interfaces and polymorphism
‘many forms’.
When you put
You can treat a Snowboard as a an object in an
Snowboard or as an Object. ArrayList<Object>, you
can treat it only as an
)F
casting objects
Wait a minute... what good Casting an object reference
is a Dog if it comes out of an back to its real type.
ArrayList<Object> and it can’t do
any Dog things? There’s gotta be a
way to get the Dog back to a state
of Dogness...
o Dog object
Object
I hope it doesn’t hurt. )T S
interfaces and polymorphism
So now you’ve seen how much Java
cares about the methods in the
class of the reference variable.
You can call a method on an object only if
the class of the reference variable has that
method.
Think of the public methods in your class as
your contract, your promise to the outside
world about the things you can do.
7HEN
modifying a class tree
What if you need to change YiX`e
the contract? gfn\i
/+
interfaces and polymorphism
Let’s explore some design options
for reusing some of our existing
classes in a PetShop program.
/N
modifying existing classes
2 Option t wo
We start with Option One, putting the pet methods
in class Animal, but we make the methods abstract,
forcing the Animal subclasses to override them.
Pros: puuiptmpephatlelelrmmete,ehntbethuapotteditwsoinatmsbh.estMtnhroaoakdcest.all
That would give us all the benefits of Option One, but with-
out the drawback of having non-pet Animals running around
with pet methods (like beFriendly()). All Animal classes
would have the method (because it’s in class Animal), but
because it’s abstract the non-pet Animal classes won’t
inherit any functionality. All classes MUST override the
methods, but they can make the methods “do-nothings”.
Cons: Animal
Because the pet methods in the Animal class are all Hippo
abstract, the concrete Animal subclasses are forced to
implement all of them. (Remember, all abstract methods
MUST be implemented by the first concrete subclass
down the inheritance tree.) What a waste of time! Canine
Dog
You have to sit there and type in each and every
pet method into each and every concrete non-
pet class, and all future subclasses as well.
And while this does solve the problem of Feline
non-pets actually DOING pet things
(as they would if they inherited pet
functionality from class Animal), the
contract is bad. Every non-pet
class would be announcing to the
world that it, too, has those Cat Wolf
pet methods, even though
the methods wouldn’t Lion
actually DO anything
when called. Tiger
This approach doesn’t Ask me to be friendly.
look good at all. It just No, seriously... ask me.
seems wrong to stuff
everything into class Animal I have the method.
that more than one Animal type
might need, UNLESS it applies to
ALL Animal subclasses.
220 chapter 8
interfaces and polymorphism
3 Option three PAinuntsitmteaahldecploaefstsienms eAtthnhaimotdascl.aOnNbLeYpeitnst, he
Put the pet methods ONLY in the Animal
classes where they belong.
Pros:
No more worries about Hippos greeting you at the
door or licking your face. The methods are where
they belong, and ONLY where they belong. Dogs can
implement the methods and Cats can implement the
methods, but nobody else has to know about them.
Cons:
Two Big Problems with this approach. First off, you’d
have to agree to a protocol, and all programmers of
pet Animal classes now and in the future would have
to KNOW about the protocol. By protocol, we mean
the exact methods that we’ve decided all pets should
have. The pet contract without anything to back it up.
But what if one of the programmers gets it just a tiny
bit wrong? Like, a method takes a String when it was
supposed to take an int? Or they named it doFriendly()
instead of beFriendly()? Since it isn’t in a contract, Canine
the compiler has no way to check you to see if you’ve Hippo
implemented the methods correctly. Someone
could easily come along to use the pet Animal
classes and find that not all of them work Feline
quite right.
Dog
And second, you don’t get to use
polymorphism for the pet methods.
Every class that needs to use
pet behaviors would have to Cat Wolf
know about each and every
class! In other words, Lion
you can’t use Animal
Tiger
as the polymorphic
type now, because the
compiler won’t let you call
a Pet method on an Animal
reference (even if it’s really a
Dog object) because class Animal
doesn’t have the method.
you are here4 221
multiple inheritance?
So what we REALLY need is:
Æ A way to have pet behavior in just the pet classes
Æ A way to guarantee that all pet classes have all of the same
methods defined (same name, same arguments, same return
types, no missing methods, etc.), without having to cross your
fingers and hope all the programmers get it right.
Æ A way to take advantage of polymorphism so that all pets can have
their pet methods called, without having to use arguments, return
types, and arrays for each and every pet class.
It looks like we need TWO
superclasses at the top
WsuegpivmeerackitleasaasllcntaewlhleedapbePsttertma, ceattnhdods. Pet Animal
Canine
Hippo
Cat Feline Dog
CfAtarNhtoemDnmobPweotetethhxo, tdAseosnnioidmtfsaglbeottsh. Lion Wolf PDetoganedxtAenndimsabloth
Tiger
222 chapter 8
The non-pet Animals
don’t have any inherited
Pet stuff.
interfaces and polymorphism
There’s just one problem with the “two superclasses” approach...
It’s called “multiple inheritance”
and it can be a Really Bad Thing.
That is, if it were possible to do in Java.
But it isn’t, because multiple inheritance has a problem
known as The Deadly Diamond of Death.
Deadly Diamond of Death
CianDmihnnedeBstrtuhibatroonndtcfeh.errBoovamoavnetrdDriharDbiiigdnlViehte.DeatrlBRihteeucrtbonhureerrdne“(bri)o”, th DigitalRecorder ImvaavannragdeiliauenbeDdelsse.VttWihDsoahBtuausutsetredhnhebeabropy“,tpi”hwbenoiivtnstahshlitufdaeCinsCfDcoofeBmferub“reoinnD”et?rrive
CDBurner int i
burn()
DVDBurner
burn() burn()
ComboDrive
cWPalhrloicbbhulerbmnu(r)wnio(tn)hmtmheuetlhtCoipodlmerbuionnDhserwriivhteea?nncyeo.u
!
interfaces
Interface to the rescue!
*AVA
interfaces and polymorphism
Making and Implementing bjsiuaeistnsebyttonslpteetsrt’rlofaiatocavonretcaese,tilnystm(fopioneoettrfftychaapehosciedhnittisgow,,naoiian.trr.n.e’d)s‘dpsiunmbibonpelt,ilccicabc’iuuotastnlneysdwiwdpe‘eeuar’bdbveleisiddctnr‘haeganevocerdotred’
the Pet interface
Yofou‘cslaayss‘’inhteerreface’ instead
public interface Pet { Aasblelsmtinirctaoeclrotfn,sa.scoRe temmheeetymhbMoedrUs,SatTrheeeyndhaivne
public abstract void beFriendly();
public abstract void play(); no body!
}
Dog DISo-gAISA-nAimPalet class Dog extends Canine implements Pet { Yfoofolultoswhaeeydi‘nibmtyeprltefmhaeecnen.tasm’ e
and
public
public void beFriendly() {...} icniYmostnopteulearmSdacAeotnIft.DNstyeohmoteuiiccPaeoerlottenhmsae.ePctuehrtol,dyssbo. rIytaoc’suesyMouUrST
public void play() {..}
public void roam() {...}
public void eat() {...} These are mjuestthondors.mal
} overriding
DtuhemrebareQnuo estions TYPES
interface polymorphism
Classes from different inheritance trees
can implement the same interface.
Robot
Pet Animal
Agent
RoboDog
Canine
gicCneohtlmaessrestitfoRarnobocbemeoaDttrohPegeeetdA,!obneuimstna’itlt still Hippo
Feline
Dog
Cat Lion Wolf
Tiger
7HEN
interfaces and polymorphism
Make it Stick
2%O*X3ASOTCEIVMENDNLSAANL
using super
Invoking the superclass abstract class Report { smutpehetarhtcoldsausbsdcovleaessrssieimosnpcoooruftladtnhtuesestuff
version of a method void runReport() {
// set-up report
Q: 7HAT
interfaces and polymorphism
BULLET POINTS Q:4HERE S