Interfaces and Inheritance

 <  Day Day Up  >  

So, what is an interface? To answer this question, let's take a look at an inheritance example: a class called Apple that is a direct descendant of the Fruit superclass. Figure 6.1 shows the Apple-Fruit inheritance hierarchy.

Figure 6.1. Apple-Fruit inheritance hierarchy.


What if we want apples to also have the capability of becoming a pie so that if apples are destined to become pies, they will have the Pie methods and attributes? If the desired outcome is to have the attributes of both classes in one, the class would have to inherit all the Fruit attributes as well as the Pie attributes, as shown in Figure 6.2. This is known as multiple inheritance.

Figure 6.2. Apple-Fruit-Pie multiple inheritance hierarchy.


Unfortunately, because multiple inheritance is not allowed, this is not a viable solution. We could, as suggested in Chapter 5, add the Pie class into the class hierarchy, as shown in Figure 6.3, but then we are assuming that all fruit types are pies.

Figure 6.3. Apple-Fruit-Pie inheritance hierarchy.


In this case, the hierarchy forces a relationship between all fruit subclasses and the Pie class. Because not all fruit types are appropriate for pies, we would be forcing relationships that don't follow the "is a kind of" test. After all, apple may be a kind of fruit, but watermelon is not always a kind of pie.


Rule of inheritance: Create a superclass-subclass relationship when you can argue that the subclass can be viewed as an instance of itself as well as an instance of the ancestor . For example: an apple "is a kind of" fruit or a garage "is a kind of" building or a car loan "is a kind of" loan.

Another solution is to implement the Pie methods only in the subclasses that will need the methods. Figure 6.4 illustrates this implementation.

Figure 6.4. Pie method implementation.


Notice that we have added an unrelated class hierarchy that may also benefit from having the Pie methods.

 <  Day Day Up  >  

Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162 © 2008-2017.
If you may any questions please contact us: