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 are comp onen ts. This idea w as the cen tral lesson in the case studies presen ted in the �rst part of the b o ok. The next step in learning ob ject-orien ted programming is organizing classes in to a hierar- c hical structure based on the concept of inheritance. By inheritanc e , w e mean the prop ert y that instances of a c hild class (or sub class) can access b oth 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 only to the creation of new classes using sub classing (the extends k eyw ord), there are n umerous corresp ondences b e- t w een sub classing and the designation that classes satisfy an in terface (the implements k ey- w ord). The latter is sometimes termed \inheritance of sp eci�cation," con trasted with the \inheritance of co de" pro vided b y sub classing. In this c hapter w e will use the w ord in a general fashion, meaning b oth mec hanisms. While the in tuitiv e meaning of inheritance is clear, and w e ha v e used inheritance in man y of our earlier case studies, and the mec hanics of using inheritance are relativ ely simple, there are nev ertheless subtle features in v olv ed in the use of inheritance in Ja v a. In this and subsequen t c hapters w e will explore some of these issues. 8.1 An In tuitiv e Description of Inheritance Let us return to Flora the �orist from the �rst c hapter. There is a certain b eha vior w e exp ect �orists to p erform, not b ecause they are �orists but simply b ecause they are shopk eep ers. F or 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 �orists, but are common to bak ers, gro cers, stationers, car dealers, and other 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 of 133
134 CHAPTER 8. UNDERST ANDING INHERIT ANCE shopk eep ers, the b eha vior is automatically iden ti�ed 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) of the prop erties asso ciated with paren t classes. A c hild class will b e giv en all the prop erties of the paren t class, and ma y in addition de�ne new prop erties. On the other hand, since a c hild class is a more sp ecialized (or restricted) form of the paren t class, it is also, in a certain sense, a c ontr action of the paren t t yp e. F or example, the Ja v a library F rame represen ts an y t yp e of windo w, but a PinBallGame frame is restricted to a single t yp e of game. This tension b et w een inheritance as expansion and inheritance as con traction is a source for m uc h of the p o 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 of the uses of 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 of class Mammal , and class Mammal is a sub class of class Animal , then Dog will inherit attributes b oth from Mammal and from Animal . A complicating factor in our in tuitiv e description of inheritance is the fact that sub classes can override b eha vior inherited from paren t classes. F or example, the class Plat ypus o v errides the repro duction b eha vior inherited from class Mammal , since plat ypuses la y eggs. W e will brie�y men tion the mec hanics of o v erriding in this c hapter, then return to a more detailed discussion of the seman tics of o v erriding in Chapter 11. 8.2 The base class Ob ject In Ja v a all classes use inheritance. Unless sp eci�ed otherwise, all classes are deriv ed from a single ro ot 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: f class FirstProgram extends Object ... // g ; The class Object pro vides minimal functionalit y guaran teed to b e common to all ob jects. These include the follo wing metho ds: equals (Object obj) Determine whether the argumen t ob ject is the same as the receiv er. This metho d is often o v erridden to c hange the equalit y test for di�eren t classes. getClass () Returns the name of the class of the receiv er as a string. hashCo de () Returns a hash v alue for this ob ject (see Section 19.7). This metho d should also b e o v erridden when the equals metho d is c hanged.
8.3. SUBCLASS, SUBTYPE, AND SUBSTITUT ABILITY 135 toString () Con v erts ob ject in to a string v alue. This metho d is also often o v erridden. 8.3 Sub class, Subt yp e, and Substitutabilit y The concept of substitutability is fundamen tal to man y of the most p o w erful soft w are dev el- opmen t tec hniques in ob ject-orien ted programming. The idea of substitutabilit y is that the t yp e giv en in a declaration of 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 o ccurrence in ob ject-orien ted programs. W e ha v e seen sev eral examples of substitutabilit y in our 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 of di�eren t t yp es of v alues that w ere created using sub classes of 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 o ccur through the use of in terfaces. An example is the instance of the class FireButtonListener created in the Cannon-ball game (Chapter 6). The class from whic h this v alue w as de�ned 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. f class CannonWorld extends Frame ... f private class FireButtonListe ner implements ActionListener public void actionPerformed (ActionEvent e) f ... g g f public CannonWorld () ... fire.addActionL ist en er( ne w FireButtonListe ne r() ); g g Because Object is a paren t class to all ob 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 of this prop ert y , holding its v alues in an arra y of Object v alues. Because the arra y is declared as Object , an y ob ject v alue can b e stored in a V ecto r .
Recommend
More recommend