
Chapter 8 Understanding Inheritance The rst step in learning ob ject-oriented programming is understanding the basic philosophy of organizing a computer program as the interaction of lo osely coupled software comp onents. This idea was the central lesson in the case studies presented in the rst part of the b o ok. The next step in learning ob ject-oriented programming is organizing classes into a hierar- chical structure based on the concept of inheritance. By inheritance,we mean the prop erty that instances of a child class or sub class can access b oth data and b ehavior metho ds asso ciated with a parent class or sup erclass. Although in Java the term inheritance is correctly applied only to the creation of new classes using sub classing the extends keyword, there are numerous corresp ondences be- tween sub classing and the designation that classes satisfy an interface the implements key- word. The latter is sometimes termed \inheritance of sp eci cation," contrasted with the \inheritance of co de" provided by sub classing. In this chapter we will use the word in a general fashion, meaning b oth mechanisms. While the intuitive meaning of inheritance is clear, and wehave used inheritance in many of our earlier case studies, and the mechanics of using inheritance are relatively simple, there are nevertheless subtle features involved in the use of inheritance in Java. In this and subsequentchapters we will explore some of these issues. 8.1 An Intuitive Description of Inheritance Let us return to Flora the orist from the rst chapter. There is a certain b ehavior we exp ect orists to p erform, not b ecause they are orists but simply b ecause they are shopkeep ers. For example, we exp ect Flora to request money for the transaction and in turn give us a receipt. These activities are not unique to orists, but are common to bakers, gro cers, stationers, car dealers, and other merchants. It is as though we have asso ciated certain b ehavior with the general category Shopkeep er, and as Florists are a sp ecialized form of 133 134 CHAPTER 8. UNDERSTANDING INHERITANCE shopkeep ers, the b ehavior is automatically identi ed with the sub class. In programming languages, inheritance means that the b ehavior and data asso ciated with child classes are always an extension that is, a larger set of the prop erties asso ciated with parent classes. A child class will b e given all the prop erties of the parent class, and may in addition de ne new prop erties. On the other hand, since a child class is a more sp ecialized or restricted form of the parent class, it is also, in a certain sense, a contraction of the parenttyp e. For example, the Java library Frame represents anytyp e of window, but a PinBallGame frame is restricted to a single typ e of game. This tension b etween inheritance as expansion and inheritance as contraction is a source for muchofthepower inherentin the technique, but at the same time it causes much confusion as to its prop er employment. We will see this when we examine a few of the uses of inheritance in a subsequent section. Inheritance is always transitive, so that a class can inherit features from sup erclasses many levels away. 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 intuitive description of inheritance is the fact that sub classes can override b ehavior inherited from parent classes. For example, the class Platypus overrides the repro duction b ehavior inherited from class Mammal, since platypuses lay eggs. We will brie y mention the mechanics of overriding in this chapter, then return to a more detailed discussion of the semantics of overriding in Chapter 11. 8.2 The base class Ob ject In Java all classes use inheritance. Unless sp eci ed otherwise, all classes are derived from a single ro ot class, named Object. If no parent class is explicitly provided, the class Object is implicitly assumed. Thus, the class declaration for FirstProgram Chapter 4, Figure 4.1 is the same as the following: class FirstProgram extends Object f // ... g; The class Object provides minimal functionality guaranteed to b e common to all ob jects. These include the following metho ds: equals Object obj Determine whether the argument ob ject is the same as the receiver. This metho d is often overridden to change the equality test for di erent classes. getClass Returns the name of the class of the receiver as a string. hashCo de Returns a hash value for this ob ject see Section 19.7. This metho d should also b e overridden when the equals metho d is changed. 8.3. SUBCLASS, SUBTYPE, AND SUBSTITUTABILITY 135 toString Converts ob ject into a string value. This metho d is also often overridden. 8.3 Sub class, Subtyp e, and Substitutability The concept of substitutability is fundamental to many of the most p owerful software devel- opment techniques in ob ject-oriented programming. The idea of substitutability is that the typ e given in a declaration of a variable may not match the typ e asso ciated with avalue the variable is holding. Note that this is never true in conventional programming languages, but is a common o ccurrence in ob ject-oriented programs. Wehave seen several examples of substitutability in our earlier case studies. In the Pin Ball game program describ ed in Chapter 7, the variable target was declared as a PinBallTar- get, but in fact held a variety of di erenttyp es of values that were created using sub classes of PinBallTarget. These target values were held in the vector named targets. PinBallTarget target = PinBallTarget targets.elementAtj; Substitutability can also o ccur through the use of interfaces. An example is the instance of the class FireButtonListener created in the Cannon-ball game Chapter 6. The class from which this value was de ned was declared as implementing the interface ActionListener. Because it implements the ActionListener interface, we can use this value as a parameter to a function in this case, addActionListener that exp ects an ActionListener value. class CannonWorld extends Frame f ... private class FireButtonListener implements ActionListener f public void actionPerformed ActionEvent e f ... g g public CannonWorld f ... fire.addActionListenernew FireButtonListener; g g Because Object is a parent class to all ob jects, avariable declared using this typ e can hold any non-primitivevalue. The collection class Vector makes use of this prop erty, holding its values in an arrayof Object values. Because the array is declared as Object,any ob ject value can b e stored in a Vector. 136 CHAPTER 8. UNDERSTANDING INHERITANCE When new classes are constructed using inheritance from existing classes, the argument used to justify the validity of substitutability is as follows: Instances of the sub class must p ossess all data areas asso ciated with the parent class. Instances of the sub class must implement, through inheritance at least if not explicitly overridden all functionality de ned for the parent class. They can also de ne new functionality, but that is unimp ortant for the argument. Thus, an instance of a child class can mimic the b ehavior of the parent class and should be indistinguishable from an instance of the parent class if substituted in a similar situation. We will see later in this chapter, when we examine the various ways in which inheritance can b e used, that this is not always a valid argument. Thus, not all sub classes formed using inheritance are candidates for substitution. The term subtype is used to describ e the relationship b etween typ es that explicitly rec- ognizes the principle of substitution. That is, a typ e B is considered to b e a subtyp e of A if two conditions hold. The rst is that an instance of B can legally b e assigned to a variable declared as typ e A. And the second is that this value can then b e used by the variable with no observable change in b ehavior. The term subclass refers merely to the mechanics of constructing a new class using inheritance, and is easy to recognize from the source description of a program by the presence of the keyword extends. The subtype relationship is more abstract, and is only lo osely do cumented directly by the program source. In the ma jority of situations a sub class is also a subtyp e. However, later in this chapter we will discover ways in which sub classes can b e formed that are not subtyp es. In addition, subtyp es can b e formed using interfaces, linking typ es that have no inheritance relationship whatso ever. So it is imp ortant to understand b oth the similarities and the di erences b etween these two concepts. 8.4 Forms of Inheritance Inheritance is employed in a surprising varietyofways. In this section we will describ e a few of its more common uses. Note that the following list represents general abstract categories and is not intended to b e exhaustive. Furthermore, it sometime happ ens that two or more descriptions are applicable to a single situation, b ecause some metho ds in a single class use inheritance in one way while others use it in another. In the following list, pay careful attention to which uses of inheritance supp ort the subtyping relationship and which do not.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages18 Page
-
File Size-