Friday 3 March 2017

Composition (HAS-A) Relationship



Composition in java can be achieved by using instance variables that refers to other objects.

Example: Car has Engine, or House has Bathroom, a Person has a Job.

class Engine {
     private String model;
     private long power;

     public long getPower() {
           return power;
     }

     public void setPower(long power) {
           this.power = power;
     }

     public String getModel() {
           return model;
     }

     public void setModel(String model) {
           this.model = model;
     }  
}

class Car {
     //composition has-a relationship
     private Engine engine;

     public Car() {

           this.engine = new Engine();
           engine.setPower(1000L);
     }

     public long getPower() {
           return engine.getPower();
     }
}

public class CompositionTest {
     public static void main(String[] args) {
           Car car = new Car();
           System.out.println("Engine Power in cc #"+car.getPower());
     }
}


Notice that above test program is not affected by any change in the Engine object. If you are looking for code reuse and the relationship between two classes is has-a then you should use composition rather than inheritance.

Biggest benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...