Chapter 8 Understanding Inheritance The rst step in learning - - PDF document

chapter 8 understanding inheritance the rst step in
SMART_READER_LITE
LIVE PREVIEW

Chapter 8 Understanding Inheritance The rst step in learning - - PDF document

Chapter 8 Understanding Inheritance The rst step in learning ob ject-orien ted programming is understanding the basic philosoph y of organizing a computer program as the in teraction of lo osely coupled soft w


slide-1
SLIDE 1 Chapter 8 Understanding Inheritance The rst step in learning
  • b
ject-orien ted programming is understanding the basic philosoph y
  • f
  • rganizing
a computer program as the in teraction
  • f
lo
  • sely
coupled soft w are comp
  • nen
ts. This idea w as the cen tral lesson in the case studies presen ted in the rst part
  • f
the b
  • k.
The next step in learning
  • b
ject-orien ted programming is
  • rganizing
classes in to a hierar- c hical structure based
  • n
the concept
  • f
inheritance. By inheritanc e, w e mean the prop ert y that instances
  • f
a c hild class (or sub class) can access b
  • th
data and b eha vior (metho ds) asso ciated with a paren t class (or sup erclass). Although in Ja v a the term inheritance is correctly applied
  • nly
to the creation
  • f
new classes using sub classing (the extends k eyw
  • rd),
there are n umerous corresp
  • ndences
b e- t w een sub classing and the designation that classes satisfy an in terface (the implements k ey- w
  • rd).
The latter is sometimes termed \inheritance
  • f
sp ecication," con trasted with the \inheritance
  • f
co de" pro vided b y sub classing. In this c hapter w e will use the w
  • rd
in a general fashion, meaning b
  • th
mec hanisms. While the in tuitiv e meaning
  • f
inheritance is clear, and w e ha v e used inheritance in man y
  • f
  • ur
earlier case studies, and the mec hanics
  • f
using inheritance are relativ ely simple, there are nev ertheless subtle features in v
  • lv
ed in the use
  • f
inheritance in Ja v a. In this and subsequen t c hapters w e will explore some
  • f
these issues. 8.1 An In tuitiv e Description
  • f
Inheritance Let us return to Flora the
  • rist
from the rst c hapter. There is a certain b eha vior w e exp ect
  • rists
to p erform, not b ecause they are
  • rists
but simply b ecause they are shopk eep ers. F
  • r
example, w e exp ect Flora to request money for the transaction and in turn giv e us a receipt. These activities are not unique to
  • rists,
but are common to bak ers, gro cers, stationers, car dealers, and
  • ther
merc han ts. It is as though w e ha v e asso ciated certain b eha vior with the general category Shopk eep er, and as Flo rists are a sp ecialized form
  • f
133
slide-2
SLIDE 2 134 CHAPTER 8. UNDERST ANDING INHERIT ANCE shopk eep ers, the b eha vior is automatically iden tied with the sub class. In programming languages, inheritance means that the b eha vior and data asso ciated with c hild classes are alw a ys an extension (that is, a larger set)
  • f
the prop erties asso ciated with paren t classes. A c hild class will b e giv en all the prop erties
  • f
the paren t class, and ma y in addition dene new prop erties. On the
  • ther
hand, since a c hild class is a more sp ecialized (or restricted) form
  • f
the paren t class, it is also, in a certain sense, a c
  • ntr
action
  • f
the paren t t yp e. F
  • r
example, the Ja v a library F rame represen ts an y t yp e
  • f
windo w, but a PinBallGame frame is restricted to a single t yp e
  • f
game. This tension b et w een inheritance as expansion and inheritance as con traction is a source for m uc h
  • f
the p
  • w
er inheren t in the tec hnique, but at the same time it causes m uc h confusion as to its prop er emplo ymen t. W e will see this when w e examine a few
  • f
the uses
  • f
inheritance in a subsequen t section. Inheritance is alw a ys transitiv e, so that a class can inherit features from sup erclasses man y lev els a w a y . That is, if class Dog is a sub class
  • f
class Mammal, and class Mammal is a sub class
  • f
class Animal, then Dog will inherit attributes b
  • th
from Mammal and from Animal. A complicating factor in
  • ur
in tuitiv e description
  • f
inheritance is the fact that sub classes can
  • verride
b eha vior inherited from paren t classes. F
  • r
example, the class Plat ypus
  • v
errides the repro duction b eha vior inherited from class Mammal, since plat ypuses la y eggs. W e will briey men tion the mec hanics
  • f
  • v
erriding in this c hapter, then return to a more detailed discussion
  • f
the seman tics
  • f
  • v
erriding in Chapter 11. 8.2 The base class Ob ject In Ja v a all classes use inheritance. Unless sp ecied
  • therwise,
all classes are deriv ed from a single ro
  • t
class, named Object. If no paren t class is explicitly pro vided, the class Object is implicitly assumed. Th us, the class declaration for FirstProgram (Chapter 4, Figure 4.1) is the same as the follo wing: class FirstProgram extends Object f // ... g; The class Object pro vides minimal functionalit y guaran teed to b e common to all
  • b
jects. These include the follo wing metho ds: equals (Object
  • bj)
Determine whether the argumen t
  • b
ject is the same as the receiv er. This metho d is
  • ften
  • v
erridden to c hange the equalit y test for dieren t classes. getClass () Returns the name
  • f
the class
  • f
the receiv er as a string. hashCo de () Returns a hash v alue for this
  • b
ject (see Section 19.7). This metho d should also b e
  • v
erridden when the equals metho d is c hanged.
slide-3
SLIDE 3 8.3. SUBCLASS, SUBTYPE, AND SUBSTITUT ABILITY 135 toString () Con v erts
  • b
ject in to a string v alue. This metho d is also
  • ften
  • v
erridden. 8.3 Sub class, Subt yp e, and Substitutabilit y The concept
  • f
substitutability is fundamen tal to man y
  • f
the most p
  • w
erful soft w are dev el-
  • pmen
t tec hniques in
  • b
ject-orien ted programming. The idea
  • f
substitutabilit y is that the t yp e giv en in a declaration
  • f
a v ariable ma y not matc h the t yp e asso ciated with a v alue the v ariable is holding. Note that this is nev er true in con v en tional programming languages, but is a common
  • ccurrence
in
  • b
ject-orien ted programs. W e ha v e seen sev eral examples
  • f
substitutabilit y in
  • ur
earlier case studies. In the Pin Ball game program describ ed in Chapter 7, the v ariable ta rget w as declared as a PinBallT a r- get, but in fact held a v ariet y
  • f
dieren t t yp es
  • f
v alues that w ere created using sub classes
  • f
PinBallT a rget. (These target v alues w ere held in the v ector named ta rgets). PinBallTarget target = (PinBallTarget) targets.elementAt (j ); Substitutabilit y can also
  • ccur
through the use
  • f
in terfaces. An example is the instance
  • f
the class FireButtonListener created in the Cannon-ball game (Chapter 6). The class from whic h this v alue w as dened w as declared as implemen ting the in terface ActionListener. Because it implemen ts the ActionListener in terface, w e can use this v alue as a parameter to a function (in this case, addActionListener) that exp ects an ActionListener v alue. class CannonWorld extends Frame f ... private class FireButtonListe ner implements ActionListener f public void actionPerformed (ActionEvent e) f ... g g public CannonWorld () f ... fire.addActionL ist en er( ne w FireButtonListe ne r() ); g g Because Object is a paren t class to all
  • b
jects, a v ariable declared using this t yp e can hold an y non-primitiv e v alue. The collection class V ecto r mak es use
  • f
this prop ert y , holding its v alues in an arra y
  • f
Object v alues. Because the arra y is declared as Object, an y
  • b
ject v alue can b e stored in a V ecto r.
slide-4
SLIDE 4 136 CHAPTER 8. UNDERST ANDING INHERIT ANCE When new classes are constructed using inheritance from existing classes, the argumen t used to justify the v alidit y
  • f
substitutabilit y is as follo ws:
  • Instances
  • f
the sub class m ust p
  • ssess
all data areas asso ciated with the paren t class.
  • Instances
  • f
the sub class m ust implemen t, through inheritance at least (if not explicitly
  • v
erridden) all functionalit y dened for the paren t class. (They can also dene new functionalit y , but that is unimp
  • rtan
t for the argumen t).
  • Th
us, an instance
  • f
a c hild class can mimic the b eha vior
  • f
the paren t class and should b e indistinguishable from an instance
  • f
the paren t class if substituted in a similar situation. W e will see later in this c hapter, when w e examine the v arious w a ys in whic h inheritance can b e used, that this is not alw a ys a v alid argumen t. Th us, not all sub classes formed using inheritance are candidates for substitution. The term subtyp e is used to describ e the relationship b et w een t yp es that explicitly rec-
  • gnizes
the principle
  • f
substitution. That is, a t yp e B is considered to b e a subt yp e
  • f
A if t w
  • conditions
hold. The rst is that an instance
  • f
B can legally b e assigned to a v ariable declared as t yp e A. And the second is that this v alue can then b e used b y the v ariable with no
  • bserv
able c hange in b eha vior. The term sub class refers merely to the mec hanics
  • f
constructing a new class using inheritance, and is easy to recognize from the source description
  • f
a program b y the presence
  • f
the k eyw
  • rd
extends. The subtyp e relationship is more abstract, and is
  • nly
lo
  • sely
do cumen ted directly b y the program source. In the ma jorit y
  • f
situations a sub class is also a subt yp e. Ho w ev er, later in this c hapter w e will disco v er w a ys in whic h sub classes can b e formed that are not subt yp es. In addition, subt yp es can b e formed using in terfaces, linking t yp es that ha v e no inheritance relationship whatso ev er. So it is imp
  • rtan
t to understand b
  • th
the similarities and the dierences b et w een these t w
  • concepts.
8.4 F
  • rms
  • f
Inheritance Inheritance is emplo y ed in a surprising v ariet y
  • f
w a ys. In this section w e will describ e a few
  • f
its more common uses. Note that the follo wing list represen ts general abstract categories and is not in tended to b e exhaustiv e. F urthermore, it sometime happ ens that t w
  • r
more descriptions are applicable to a single situation, b ecause some metho ds in a single class use inheritance in
  • ne
w a y while
  • thers
use it in another. In the follo wing list, pa y careful atten tion to whic h uses
  • f
inheritance supp
  • rt
the subt yping relationship and whic h do not. 8.4.1 Inheritance for Sp ecialization Probably the most common use
  • f
inheritance and sub classing is for sp ecialization. In this form, the new class is a sp ecialized v ariet y
  • f
the paren t class but satises the sp ecications
slide-5
SLIDE 5 8.4. F ORMS OF INHERIT ANCE 137
  • f
the paren t in all relev an t resp ects. Th us, this form alw a ys creates a subt yp e, and the principle
  • f
substitutabilit y is explicitly upheld. Along with the follo wing category (sub- classing for sp ecication) this is the most ideal form
  • f
inheritance, and something that a go
  • d
design should striv e for. The creation
  • f
application windo w classes using inheritance from the Ja v a library class F rame is an example
  • f
sub classing for sp ecialization. The follo wing is from the PinBall Game program in Chapter 7. public class PinBallGame extends Frame f ... g T
  • run
suc h an application an instance
  • f
PinBallGame is rst created. V arious metho ds inherited from class F rame, suc h as setSize, setTitle, and sho w, are then in v
  • k
ed. These metho ds do not realize they are manipulating an instance
  • f
PinBallGame, but instead act as if they w ere
  • p
erating
  • n
an instance
  • f
F rame. The actions they p erform w
  • uld
b e the same for an y instance
  • f
class F rame. Where application sp ecic b eha vior is necessary , for example, in repain ting the windo w, a metho d is in v
  • k
ed that is
  • v
erridden b y the application class. F
  • r
example, the metho d in the paren t class will in v
  • k
e the metho d repaint. Although the paren t class F rame p
  • ssesses
a metho d
  • f
this name, the paren t metho d is not the
  • ne
executed. Instead, the function dened in the c hild class is executed. W e sa y that sub classing for sp ecialization is
  • ccurring
in this example b ecause the c hild class (in this example, PinBallGame) satises all the prop erties that w e exp ect
  • f
the paren t class (F rame). In addition, the new class
  • v
errides
  • ne
  • r
more metho ds, sp ecializing them with application-sp ecic b eha vior. 8.4.2 Inheritance for Sp ecication Another frequen t use for inheritance is to guaran tee that classes main tain a certain common in terface{that is, they implemen t the same metho ds. The paren t class can b e a com bination
  • f
implemen ted
  • p
erations and
  • p
erations that are deferred to the c hild classes. Often, there is no in terface c hange
  • f
an y sort b et w een the paren t class and the c hild class{the c hild merely implemen ts b eha vior describ ed, but not implemen ted, in the paren t. This is actually a sp ecial case
  • f
sub classing for sp ecialization, except that the sub classes are not renemen ts
  • f
an existing t yp e but rather realizations
  • f
an incomplete abstract sp ecication. That is, the paren t class denes the
  • p
eration, but has no implemen tation. It is
  • nly
the c hild class that pro vides an implemen tation. In suc h cases the paren t class is sometimes kno wn as an abstr act sp e cic ation class. There are t w
  • dieren
t mec hanisms pro vided b y the Ja v a language to supp
  • rt
the idea
  • f
inheritance
  • f
sp ecication. The most
  • b
vious tec hnique is the use
  • f
in terfaces. W e ha v e seen examples
  • f
this in the w a y that ev en ts are handled b y the Ja v a library . F
  • r
slide-6
SLIDE 6 138 CHAPTER 8. UNDERST ANDING INHERIT ANCE instance, the c haracteristics needed for an ActionListener (the
  • b
ject t yp e that resp
  • nds
to button presses) can b e describ ed b y a single metho d, and the implemen tation
  • f
that metho d cannot b e predicted, since it diers from
  • ne
application to another. Th us, an interface is used to describ e
  • nly
the necessary requiremen ts, and no actual b eha vior is inherited b y a sub class that implemen ts the b eha vior. interface ActionListener f public void actionPerformed (ActionEvent e); g When a button is created, an asso ciated listener class is dened. The listener class pro vides the sp ecic b eha vior for the metho d in the con text
  • f
the curren t application. class CannonWorld extends Frame f ... // a re button listener implemen ts the action listener in terface private class FireButtonListe ner implements ActionListener f public void actionPerformed (ActionEvent e) f ... // action to p erform in resp
  • nse
to button press g g g Sub classing for sp ecication can also tak e place with inheritance
  • f
classes formed using extension. One w a y to guaran tee that a sub class m ust b e constructed is to use the k eyw
  • rd
abstract. A class declared as abstract m ust b e sub classed; it is not p
  • ssible
to create an instance
  • f
suc h a class using the
  • p
erator new. In addition, individual metho ds can also b e declared as abstract, and they , to
  • ,
m ust b e
  • v
erridden b efore instances can b e constructed. An example abstract class in the Ja v a library is Numb er, a paren t class for the n umeric wrapp er classes Integer, Long, Double and so
  • n.
The class description is as follo ws: public abstract class Number f public abstract int intValue(); public abstract long longValue(); public abstract float floatValue(); public abstract double doubleValue(); public byte byteValue()
slide-7
SLIDE 7 8.4. F ORMS OF INHERIT ANCE 139 f return (byte) intValue(); g public short shortValue() f return (short) intValue(); g g Sub classes
  • f
Numb er m ust
  • v
erride the metho ds intV alue, longV alue,
  • atV
alue and doubleV alue. Notice that not all metho ds in an abstract class m ust themselv es b e declared abstract. Sub classes
  • f
Numb er need not
  • v
erride b yteV alue
  • r
sho rtV alue, as these metho ds are pro vided with an implemen tation that can b e inherited without c hange. In general, sub classing for sp ecication can b e recognized when the paren t class do es not implemen t actual b eha vior but merely denes the b eha vior that m ust b e implemen ted in c hild classes. 8.4.3 Inheritance for Construction A class can
  • ften
inherit almost all
  • f
its desired functionalit y from a paren t class, p erhaps c hanging
  • nly
the names
  • f
the metho ds used to in terface to the class,
  • r
mo difying the argumen ts. This ma y b e true ev en if the new class and the paren t class fail to share an y relationship as abstract concepts. An example
  • f
sub classing for construction
  • ccurred
in the Pin ball game application describ ed in Chapter 7. In that program, the class Hole w as declared as a sub class
  • f
Ball. There is no logical relationship b et w een the concepts
  • f
a Ball and a Hole, but from a practical p
  • in
t
  • f
view m uc h
  • f
the b eha vior needed for the Hole abstraction matc hes the b eha vior
  • f
the class Ball. Th us, using inheritance in this situation reduces the amoun t
  • f
w
  • rk
necessary to dev elop the class Hole. class Hole extends Ball implements PinBallTarget f public Hole (int x, int y) f super (x, y, 12); setColor (Color.black); g public boolean intersects (Ball aBall) f return location.interse ct s(a Ba ll. lo ca tio n) ; g public void hitBy (Ball aBall) f // mo v e ball totally
  • frame
aBall.moveTo (0, PinBallGame.Fra meH ei ght + 30); // stop motion
  • f
ball aBall.setMotion (0, 0);
slide-8
SLIDE 8 140 CHAPTER 8. UNDERST ANDING INHERIT ANCE g g Another example
  • f
inheritance for construction
  • ccurs
in the Ja v a Library . There, the class Stack is constructed using inheritance from the class V ecto r: class Stack extends Vector f public Object push(Object item) f addElement(item) ; return item; g public boolean empty () f return isEmpty(); g public synchronized Object pop() f Object
  • bj
= peek(); removeElementAt (si ze ()
  • 1);
return
  • bj;
g public synchronized Object peek() f return elementAt(size()
  • 1);
g g As abstractions, the concept
  • f
the stac k and the concept
  • f
a v ector ha v e little in common; ho w ev er from a pragmatic p
  • in
t
  • f
view using the V ecto r class as a paren t greatly simplies the implemen tation
  • f
the stac k. Inheritance for construction is sometimes fro wned up
  • n,
since it
  • ften
directly breaks the principle
  • f
substitutabilit y (forming sub classes that are not subt yp es). On the
  • ther
hand, b ecause it is
  • ften
a fast and easy route to dev eloping new data abstractions, it is nev ertheless widely used. In Chapter 10 w e will discuss the construction
  • f
the Stack abstraction in more detail. 8.4.4 Inheritance for Extension Sub classing for extension
  • ccurs
when a c hild class
  • nly
adds new b eha vior to the paren t class, and do es not mo dify
  • r
alter an y
  • f
the inherited attributes. An example
  • f
inheritance for extension in the Ja v a library is the class Prop erties, whic h inherits from class HashT able. A hash table is a dictionary structure (see Section 19.7). A dictionary stores a collection
  • f
k ey/v alue pairs, and allo ws the user to retriev e the v alue asso ciated with a giv en k ey . Prop erties represen t information concerning the curren t execution en vironmen t. Examples
  • f
prop erties are the name
  • f
the user running the Ja v a program, the v ersion
  • f
the Ja v a
slide-9
SLIDE 9 8.4. F ORMS OF INHERIT ANCE 141 in terpreter b eing used, the name
  • f
the
  • p
erating system under whic h the Ja v a program is running, and so
  • n.
The class Prop erties uses the paren t class, HashT able, to store and retriev e the actual prop ert y name/v alue pairs. In addition, the class denes a few metho ds sp ecic to the task
  • f
managing prop erties, suc h as reading
  • r
writing prop erties to
  • r
from a le. class Properties extends Hashtable f ... public synchronized void load(InputStream in) throws IOException f ... g public synchronized void save(OutputStrea m
  • ut,
String header) f ... g public String getProperty(Str ing key) f ... g public Enumeration propertyNames() f ... g public void list(PrintStream
  • ut)
f ... g g As the functionalit y
  • f
the paren t remains a v ailable and un touc hed, sub classing for extension do es not con tra v ene the principle
  • f
substitutabilit y and so suc h sub classes are alw a ys subt yp es. 8.4.5 Inheritance for Limitation Sub classing for limitation
  • ccurs
when the b eha vior
  • f
the sub class is smaller
  • r
more restrictiv e than the b eha vior
  • f
the paren t class. Lik e sub classing for extension, sub classing for limitation
  • ccurs
most frequen tly when a programmer is building
  • n
a base
  • f
existing classes that should not,
  • r
cannot, b e mo died. There are no examples
  • f
sub classing for limitation in the Ja v a library , ho w ev er w e could imagine the follo wing. Supp
  • se
  • ne
w an ted to create the class Set, in a fashion similar to the w a y the class Stack is sub classed from V ecto r. Ho w ev er, y
  • u
also w an ted to ensur e that
  • nly
Set
  • p
erations w ere used
  • n
the set, and not v ector
  • p
erations. One w a y to accomplish this w
  • uld
b e to
  • v
erride the undesired metho ds, so that if they w ere executed they w
  • uld
generate an exception. 1 class Set extends Vector f // metho ds addElemen t, remo v eElemen t, con tains 1 In actualit y , the metho ds indexOf and elementA t are declared as nal in class V ecto r, so this example will not compile. But it do es illustrate the concept.
slide-10
SLIDE 10 142 CHAPTER 8. UNDERST ANDING INHERIT ANCE // isEmpt y and size // are all inherited from v ector public int indexOf (Object
  • bj)
f throw new IllegalOperatio n(" in dex Of ") ; g public int elementAt (int index) f throw new IllegalOperatio n(" in dex Of ") ; g g Where IllegalOp eration is a sub class
  • f
Exception: class IllegalOperatio n extends Exception f IllegalOperation (String str) f super(str); g g Sub classing for limitation is c haracterized b y the presence
  • f
metho ds that tak e a pre- viously p ermitted
  • p
eration and mak es it illegal. Because sub classing for limitation is an explicit con tra v en tion
  • f
the principle
  • f
substitutabilit y , and b ecause it builds sub classes that are not subt yp es, it should b e a v
  • ided
whenev er p
  • ssible.
8.4.6 Inheritance for Com bination When discussion abstract concepts, it is common for a new abstraction to b e formed as a com bination
  • f
features from t w
  • r
more abstractions. A teac hing assistan t, for example, ma y ha v e c haracteristics
  • f
b
  • th
a teac her and a studen t, and can therefore logically b eha v e as b
  • th.
The abilit y
  • f
a class to inherit from t w
  • r
more paren t classes is kno wn as multiple inheritanc e. Although the Ja v a language do es not p ermit a sub class to b e formed b y inheritance from more than
  • ne
paren t class, sev eral appro ximations to the concept are p
  • ssible.
F
  • r
example, it is common for a new class to b
  • th
extend an existing class and implemen t an in terface. W e sa w this in the example
  • f
the class Hole that b
  • th
extended class Ball and implemen ted the in terface for PinBallT a rget. class Hole extends Ball implements PinBallTarget f ... g It is also p
  • ssible
for classes to implemen t more than
  • ne
in terface, and th us b e view ed as a com bination
  • f
the t w
  • categories.
Man y examples
  • ccur
in the input/output sections
  • f
the Ja v a Library . A RandomAccessFile, for example, implemen ts b
  • th
the DataInput and DataOutput proto cols.
slide-11
SLIDE 11 8.5. MODIFIERS AND INHERIT ANCE 143 8.4.7 Summary
  • f
the F
  • rms
  • f
Inheritance W e can summarize the v arious forms
  • f
inheritance b y the follo wing table:
  • Sp
ecialization. The c hild class is a sp ecial case
  • f
the paren t class; in
  • ther
w
  • rds,
the c hild class is a subt yp e
  • f
the paren t class.
  • Sp
ecication. The paren t class denes b eha vior that is implemen ted in the c hild class but not in the paren t class.
  • Construction.
The c hild class mak es use
  • f
the b eha vior pro vided b y the paren t class, but is not a subt yp e
  • f
the paren t class.
  • Extension.
The c hild class adds new functionalit y to the paren t class, but do es not c hange an y inherited b eha vior.
  • Limitation.
The c hild class restricts the use
  • f
some
  • f
the b eha vior inherited from the paren t class.
  • Combination.
The c hild class inherits features from more than
  • ne
paren t class. Al- though m ultiple inheritance is not supp
  • rted
directly b y Ja v a, it can b e sim ulated in part b y classes that use b
  • th
inheritance and implemen tation
  • f
an in terface,
  • r
implemen t t w
  • r
more in terfaces. The Ja v a language implicitly assumes that sub classes are also subt yp es. This means that an instance
  • f
a sub class can b e assigned to a v ariable declared as the paren t class t yp e. Metho ds in the c hild class that ha v e the same name as those in the paren t class
  • v
erride the inherited b eha vior. W e ha v e seen that this assumption that sub classes are subt yp es is not alw a ys v alid, and creating sub classes that are not subt yp es is a p
  • ssible
source
  • f
program error. 8.5 Mo diers and Inheritance The language Ja v a pro vides sev eral mo diers that can b e used to alter asp ects
  • f
the inher- itance pro cess. F
  • r
example, in the case studies in earlier c hapters, w e made extensiv e use
  • f
the visibilit y (or access con trol) mo diers public, p rotected and p rivate.
  • A
public feature (data eld
  • r
metho d) can b e accessed
  • utside
the class denition. A public class can b e accessed
  • utside
the pac k age in whic h it is declared.
  • A
p rotected feature can b e accessed
  • nly
within the class denition in whic h it app ears,
  • r
within the denition
  • f
sub classes.
  • A
p rivate feature can b e accessed
  • nly
within the class denition in whic h it app ears.
slide-12
SLIDE 12 144 CHAPTER 8. UNDERST ANDING INHERIT ANCE W e ha v e seen from
  • ur
rst case studies ho w b
  • th
metho ds and data elds can b e declared as static. A static eld is shared b y all instances
  • f
a class. A static metho d can b e in v
  • k
ed ev en when no instance
  • f
the class has b een created. Static data elds and metho ds are inherited in the same manner as non-static items, except that static metho ds cannot b e
  • v
erridden. Both metho ds and classes can b e declared to b e abstract. An abstract class cannot b e instanciated. That is, it is not legal to create an instance
  • f
an abstraction class using the
  • p
erator new. Suc h a class can
  • nly
b e used as a paren t class, to create a new t yp e
  • f
  • b
ject. Similarly , an abstract metho d m ust b e
  • v
erridden b y a sub class. An alternativ e mo dier, nal, is the
  • pp
  • site
  • f
abstract. When applied to a class, the k eyw
  • rd
indicates that the class c annot b e sub classed. Similarly , when applied to a metho d, the k eyw
  • rd
indicates that the metho d cannot b e
  • v
erridden. Th us, the user is guaran teed that the b eha vior
  • f
the class will b e as dened and not mo died b y a later sub class. final class newClass extends
  • ldClass
f ... g W e ha v e seen that program constan ts are generally dened b y v ariables that are b
  • th
static and nal: class CannonGame extends Frame f ... public static final int FrameWidth = 600; public static final int FrameHeight = 400; ... g Optimizing compilers can sometimes mak e use
  • f
the fact that a data eld, class
  • r
metho d is declared as nal, and generate b etter co de than w
  • uld
  • therwise
b e p
  • ssible.
8.6 Programming as a Multi P erson Activit y When programs are constructed
  • ut
  • f
reusable,
  • -the-shelf
comp
  • nen
ts, programming mo v es from an individual activit y (one programmer and the computer) to a comm unit y eort. A programmer ma y
  • p
erate b
  • th
as the develop er
  • f
new abstractions, and as the user
  • f
a soft w are system created b y an earlier programmer. The reader should not confuse the term user when applied to a programmer with the same term denoting the application end-user. Similarly , w e will
  • ften
sp eak
  • f
the
  • rganization
  • f
sev eral
  • b
jects b y describing a client
  • b
ject, that is requesting the services
  • f
a pr
  • vider.
Again, the clien t in this case is lik ely a programmer (or the co de b eing dev elop ed b y a programmer) making use
  • f
the
slide-13
SLIDE 13 8.7. THE BENEFITS OF INHERIT ANCE 145 services dev elop ed b y an earlier programmer. This should not b e confused with the idea
  • f
client/sever computing, as describ ed in Chapter 2. 8.7 The Benets
  • f
Inheritance In this section w e will describ e some
  • f
the man y imp
  • rtan
t b enets
  • f
the prop er use
  • f
inheritance. 8.7.1 Soft w are Reusabilit y When b eha vior is inherited from another class, the co de that pro vides that b eha vior do es not ha v e to b e rewritten. This ma y seem
  • b
vious, but the implications are imp
  • rtan
t. Man y programmers sp end m uc h
  • f
their time rewriting co de they ha v e written man y times b efore{for example, to searc h for a pattern in a string
  • r
to insert a new elemen t in to a table. With
  • b
ject-orien ted tec hniques, these functions can b e written
  • nce
and reused. 8.7.2 Increased Reliabilit y Co de that is executed frequen tly will tend to ha v e few er bugs then co de that executed infrequen tly . When the same comp
  • nen
ts are used in t w
  • r
more applications, the co de will b e exercised more than co de that is dev elop ed for a single application. Th us, bugs in suc h co de tend to b e more quic kly disco v ered, and latter applications gain the b enet
  • f
using comp
  • nen
ts are more error free. Similarly , the costs
  • f
main tenance
  • f
shared comp
  • nen
ts can b e split among man y pro jects. 8.7.3 Co de Sharing Co de sharing can
  • ccur
  • n
sev eral lev els with
  • b
ject-orien ted tec hniques. On
  • ne
lev el, man y users
  • r
pro jects can use the same classes. (Brad Co x [Co x 1986 ] calls these soft w are- ICs, in analogy to the in tegrated circuits used in hardw are design). Another form
  • f
sharing
  • ccurs
when t w
  • r
more classes dev elop ed b y a single programmer as part
  • f
a pro ject inherit from a single paren t class. F
  • r
example, a Set and an Arra y ma y b
  • th
b e considered a form
  • f
Collection. When this happ ens, t w
  • r
more t yp es
  • f
  • b
jects will share the co de that they inherit. This co de needs to b e written
  • nly
  • nce
and will con tribute
  • nly
  • nce
to the size
  • f
the resulting program. 8.7.4 Consistency
  • f
In terface When t w
  • r
more classes inherit from the same sup erclass, w e are assured that the b eha vior they inherit will b e the same in all cases. Th us, it is easier to guaran tee that in terfaces to similar
  • b
jects are in fact similar, and that the user is not presen ted with a confusing
slide-14
SLIDE 14 146 CHAPTER 8. UNDERST ANDING INHERIT ANCE collection
  • f
  • b
jects that are almost the same but b eha v e, and are in teracted with, v ery dieren tly . 8.7.5 Soft w are Comp
  • nen
ts Inheritance pro vides programmers with the abilit y to construct reusable soft w are comp
  • nen
ts. The goal is to p ermit the dev elopmen t
  • f
new and no v el applications that nev ertheless require little
  • r
no actual co ding. The Ja v a library pro vides a ric h collection
  • f
soft w are comp
  • nen
ts for use in the dev elopmen t
  • f
applications. 8.7.6 Rapid Protot yping When a soft w are system is constructed largely
  • ut
  • f
reusable comp
  • nen
ts, dev elopmen t time can b e concen trated
  • n
understanding the new and un usual p
  • rtion
  • f
the system. Th us, soft w are systems can b e generated more quic kly and easily , leading to a st yle
  • f
programming kno wn as r apid pr
  • totyping
  • r
explor atory pr
  • gr
amming. A protot yp e system is dev elop ed, users exp erimen t with it, a second system is pro duced that is based
  • n
exp erience with the rst, further exp erimen tation tak es place, and so
  • n
for sev eral iterations. Suc h programming is particularly useful in situations where the goals and requiremen ts
  • f
the system are
  • nly
v aguely understo
  • d
when the pro ject b egins. 8.7.7 P
  • lymorphism
and F ramew
  • rks
Soft w are pro duced con v en tionally is generally written from the b
  • ttom
up, although it ma y b e designe d from the top do wn. That is, the lo w er-lev el routines are written, and
  • n
top
  • f
these sligh tly higher abstractions are pro duced, and
  • n
top
  • f
these ev en more abstract elemen ts are generated. This pro cess is lik e building a w all, where ev ery bric k m ust b e laid
  • n
top
  • f
an already laid bric k. Normally , co de p
  • rtabilit
y decreases as
  • ne
mo v es up the lev els
  • f
abstraction. That is, the lo w est-lev el routines ma y b e used in sev eral dieren t pro jects, and p erhaps ev en the next lev el
  • f
abstraction ma y b e reused, but the higher-lev el routines are in timately tied to a particular application. The lo w er-lev el pieces can b e carried to a new system and generally mak e sense standing
  • n
their
  • wn;
the higher-lev el comp
  • nen
ts generally mak e sense (b ecause
  • f
declarations
  • r
data dep endencies)
  • nly
when they are built
  • n
top
  • f
sp ecic lo w er-lev el units. P
  • lymorphism
in programming languages p ermits the programmer to generate high-lev el reusable comp
  • nen
ts that can b e tailored to t dieren t applications b y c hanges in their lo w-lev el parts. The Ja v a A WT is an example
  • f
a large soft w are framew
  • rk
that relies
  • n
inheritance and substitutabilit y for its
  • p
eration.
slide-15
SLIDE 15 8.8. THE COSTS OF INHERIT ANCE 147 8.7.8 Information Hiding A programmer who reuses a soft w are comp
  • nen
t needs
  • nly
to understand the nature
  • f
the comp
  • nen
t and its in terface. It is not necessary for the programmer to ha v e detailed information concerning matters suc h as the tec hniques used to implemen t the comp
  • nen
t. Th us, the in terconnectedness b et w een soft w are systems is reduced. W e earlier iden tied the in terconnected nature
  • f
con v en tional soft w are as b eing
  • ne
  • f
the principle causes
  • f
soft w are complexit y . 8.8 The Costs
  • f
Inheritance Although the b enets
  • f
inheritance in
  • b
ject-orien ted programming are great, almost noth- ing is without cost
  • f
  • ne
sort
  • r
another. F
  • r
this reason, w e m ust consider the cost
  • f
  • b
ject-orien ted programming tec hniques, and in particular the cost
  • f
inheritance. 8.8.1 Execution Sp eed It is seldom p
  • ssible
for general-purp
  • se
soft w are to
  • ls
to b e as fast as carefully hand- crafted systems. Th us, inherited metho ds, whic h m ust deal with arbitrary sub classes, are
  • ften
slo w er than sp ecialized co de. Y et, concern ab
  • ut
eciency is
  • ften
misplaced. 2 First, the dierence is
  • ften
small. Second, the reduction in execution sp eed ma y b e balanced b y an increase in the sp eed
  • f
soft w are dev elopmen t. Finally , most programmers actually ha v e little idea
  • f
ho w execution time is b eing used in their programs. It is far b etter to dev elop a w
  • rking
system, monitor it to disco v er where execution time is b eing used, and impro v e those sections, than to sp end an inordinate amoun t
  • f
time w
  • rrying
ab
  • ut
eciency early in a pro ject. 8.8.2 Program Size The use
  • f
an y soft w are library frequen tly imp
  • ses
a size p enalt y not imp
  • sed
b y systems constructed for a sp ecic pro ject. Although this exp ense ma y b e substan tial, as memory costs decrease the size
  • f
programs b ecomes less imp
  • rtan
t. Con taining dev elopmen t costs and pro ducing high-qualit y and error-free co de rapidly are no w more imp
  • rtan
t than limiting the size
  • f
programs. 8.8.3 Message-P assing Ov erhead Muc h has b een made
  • f
the fact that message passing is b y nature a more costly
  • p
eration than simple pro cedure in v
  • cation.
As with
  • v
erall execution sp eed, ho w ev er,
  • v
erconcern 2 The follo wing quote from an article b y Bill W ulf
  • ers
some apt remarks
  • n
the imp
  • rtance
  • f
eciency: \More computing sins are committed in the name
  • f
eciency (without necessarily ac hieving it) than for an y
  • ther
single reason{including blind stupidit y" [W ulf 1972 ].
slide-16
SLIDE 16 148 CHAPTER 8. UNDERST ANDING INHERIT ANCE ab
  • ut
the cost
  • f
message passing is frequen tly p enn y-wise and p
  • und-fo
  • lish.
F
  • r
  • ne
thing, the increased cost is
  • ften
marginal{p erhaps t w
  • r
three additional assem bly-language instructions and a total time p enalt y
  • f
10 p ercen t. This increased cost, lik e
  • thers,
m ust b e w eighed against the man y b enets
  • f
the
  • b
ject-orien ted tec hnique. 8.8.4 Program Complexit y Although
  • b
ject-orien ted programming is
  • ften
touted as a solution to soft w are complexit y , in fact,
  • v
eruse
  • f
inheritance can
  • ften
simply replace
  • ne
form
  • f
complexit y with another. Understanding the con trol
  • w
  • f
a program that uses inheritance ma y require sev eral m ultiple scans up and do wn the inheritance graph. This is what is kno wn as the yo-yo problem, whic h w e will discuss in more detail in a later c hapter. 8.9 Chapter Summary Inheritance is a mec hanism for relating a new soft w are abstraction b eing dev elop ed to an
  • lder,
existing abstraction. By stating that the new comp
  • nen
t inherits (or extends) the
  • lder
abstraction, the programmer means that all the public and protected prop erties
  • f
the
  • riginal
class are also no w part
  • f
the new abstraction. In addition, the new class can add new data elds and b eha vior, and can
  • v
erride metho ds that are inherited from the
  • riginal
class. In terfaces are a closely related mec hanism, whic h tie the concrete realization
  • f
b eha vior to an abstract description. All classes in Ja v a use inheritance. If not explicitly stated, classes are assumed to inherit from the fundamen tal ro
  • t
class Object. Inheritance is tied to the principle
  • f
substitutabilit y . A v ariable that is declared as
  • ne
class can b e assigned a v alue that created from a c hild class. A similar mec hanism also w
  • rks
with in terfaces. A class that can b e used in lieu
  • f
another class is said to b e a subtyp e. Ja v a implicitly assumes that all sub classes are subt yp es. Ho w ev er, this need not b e true (a sub class can
  • v
erride a metho d in an incompatible fashion, for example). Subt yp es can also b e constructed from in terfaces, a v
  • iding
sub classes altogether. There are man y dieren t t yp es
  • f
inheritance, used for dieren t purp
  • ses.
V ariations include sp ecialization, sp ecication, construction, extension, limitation, and com bination. A v ariet y
  • f
mo diers alter the meaning
  • f
inheritance. A p rivate feature is not inherited b y sub classes. A static feature (data eld
  • r
metho d) is shared b y all instances. An abstract metho d m ust b e
  • v
erridden. A nal feature (data eld
  • r
metho d) cannot b e
  • v
erridden. Study Questions 1. Giv e an in tuitiv e description
  • f
inheritance. 2. What do es it mean for a metho d to
  • v
erride an inherited metho d?
slide-17
SLIDE 17 EXER CISES 149 3. What is the name
  • f
the ro
  • t
class for all
  • b
jects in Ja v a? 4. What b eha vior is pro vided b y the ro
  • t
class in Ja v a? 5. What do es it mean to sa y that c hild classes are substitutable for paren t classes in Ja v a? 6. What is the dierence b et w een a sub class and a subt yp e? 7. What are the c haracteristics
  • f
inheritance for sp ecialization? 8. What are the c haracteristics
  • f
inheritance for sp ecication? Ho w do es this dier from inheritance for sp ecialization? 9. What are the c haracteristics
  • f
inheritance for construction? Wh y is this not generally considered to b e a go
  • d
use
  • f
inheritance? 10. What are the c haracteristics
  • f
inheritance for extension? 11. What are the c haracteristics
  • f
inheritance for limitation? Wh y is this not generally considered to b e a go
  • d
use
  • f
inheritance? 12. Wh y w
  • uld
it not mak e sense for a metho d in Ja v a to b e declared b
  • th
abstract and nal ? 13. What are some
  • f
the b enets
  • f
dev eloping classes using inheritance, rather than dev eloping eac h new class from scratc h? 14. What are some
  • f
the costs
  • f
using inheritance for soft w are dev elopmen t? Exercises 1. Supp
  • se
y
  • u
w ere required to program a pro ject in a non-ob ject
  • rien
ted language, suc h as P ascal
  • r
C. Ho w w
  • uld
y
  • u
sim ulate the notion
  • f
classes and metho ds? Ho w w
  • uld
y
  • u
sim ulate inheritance? Could y
  • u
supp
  • rt
m ultiple inheritance? Explain y
  • ur
answ er. 2. W e noted that the execution
  • v
erhead asso ciated with message passing is t ypically greater than the
  • v
erhead asso ciated with a con v en tional pro cedure call. Ho w migh t y
  • u
measure these
  • v
erheads? F
  • r
a language that supp
  • rts
b
  • th
classes and pro ce- dures (suc h as C ++
  • r
Ob ject P ascal), devise an exp erimen t to determine the actual p erformance p enalt y
  • f
message passing.
slide-18
SLIDE 18 150 CHAPTER 8. UNDERST ANDING INHERIT ANCE 3. Consider the three geometric concepts
  • f
a line (innite in b
  • th
directions), a ra y (xed at a p
  • in
t, innite in
  • ne
direction), and a segmen t (a p
  • rtion
  • f
a line with xed end p
  • in
ts). Ho w migh t y
  • u
structure classes represen ting these three concepts in an inheritance hierarc h y? W
  • uld
y
  • ur
answ er dier if y
  • u
concen trated more
  • n
the data represen tation
  • r
more
  • n
the b eha vior? Characterize the t yp e
  • f
inheritance y
  • u
w
  • uld
use. Explain the reasoning b ehind y
  • ur
design. 4. Wh y is the example used in the follo wing explanation not a v alid illustration
  • f
inher- itance? P erhaps the most p
  • w
erful concept in
  • b
ject-orien ted programming sys- tems is inheritance. Ob jects can b e created b y inheriting the prop erties
  • f
  • ther
  • b
jects, th us remo ving the need to write an y co de whatso ev er! Sup- p
  • se,
for example, a program is to pro cess complex n um b ers consisting
  • f
real and imaginary parts. In a complex n um b er, the real and imaginary parts b eha v e lik e real n um b ers, so all
  • f
the
  • p
erations (+,
  • ,
/, *, sqrt, sin, cos, etc.) can b e inherited from the class
  • f
  • b
jects call REAL, instead
  • f
ha ving to b e written in co de. This has a ma jor impact
  • n
programmer pro ductivit y .