Witscale Test Center

11.2 Composition and generalization > 11.2.4 Implementing HAS-A relationship


11.2.4 Implementing HAS-A relationship

You can implement the HAS-A relationship by declaring object reference variables as members of a class. We have seen earlier how Car has the HAS-A relationship with a car engine. Figure 11.5 illustrates how to implement this  relationship in Java.


 

Figure 11.5 Implementing the HAS-A relationship in Java

 

You can apply the steps illustrated in figure 11.5 while implementing the Car class. Since problem definition says “A Car HAS-AN engine, battery etc”', the implementation will have a Car class with member variables of each of these types. Following code snippet implements the Car class.

 

public class Car {

  private Engine engine;

  private Battery battery;

  private WindShield windshield;

}

 

The Car class then use the functionalities of Engine class, Windshield class etc by calling their methods from the Car class. The basic reason for composition is to reuse the code. The Car class can reuse the functionality already defined in Engine class. For instance if a Car needs to needs to be driven, it can use the engine functionality as:

 

public class Car {

  private Engine engine;

  pulic void drive() {

     engine.start();                        

     engine.putIntoGear();

  }

}

 

Thus the Car class does not need to re-implement the Engine class’s functionality. With HAS-A relationship the discussion of code reuse is coming to an end. We saw how the code is reused with either inheritance (IS-A relationship) and composition (HAS-A) relationship. The reused code is better tested and flexible for modifications. Interestingly there are few other things that can be reused. Say for instance the method-names. The next section discusses how and why we need to reuse the method names.

 

Exam tests your knowledge of IS-A and HAS-A relationships by providing you the problem definition or design statements. Then you are asked how you would correctly implement it in Java. It is fairly easy if you use a simple rule of thumb. Read the problem definition carefully. The term before IS-A represents a class and the term after IS-A represents its superclass. Similarly a term just before HAS-A represents a class and all the terms after HAS-A represent its member variables.