Witscale Test Center

11.2 Composition and generalization > 11.2.2 Implementing IS-A relationship


11.2.2 Implementing IS-A relationship


You can establish the generalization relationship with the help of inheritance. Since the specialized classes (also called as subclasses) inherit behavior from a generalized superclass, you will always find that a subclass is a-special-case-of the superclass. Therefore, if the problem definition says 'A dog IS AN animal', you should implement it with a Animal class  and declare the Dog class as its subclass.  Figure 11.3 illustrates how to implement the IS-A relationship with inheritance.

 

 

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.