|
![]() |
Figure 11.3 Implementing the IS-A relationship in Java
You can apply the steps illustrated in figure 11.3 while implementing the Dog class. Since problem definition says “A dog IS-AN animal”', the implementation will have a Animal class and Dog class as its subclass.
public class Animal {
// Common animal behavior
}
public class Dog extends Animal {
// Specialized behavior for Dog
}
Subclass Dog implements specialized behavior and inherits the common animal behavior. Thus the implementation of IS-A relationship using inheritance makes it possible to reuse the common behavior. The code reuse is one of the most desired features of object-oriented languages. When code is reused, maintaining it is simpler as whenever changes are desired, you need to do changes only at one place. For example, if you change animal behavior, you need to do changes only in Animal class and rest of the subclasses with inherit the changed behavior. Thus code reuse results in better design and therefore it is easier to maintain. There is another way of reusing code besides generalization, the composition.