Composition in java with examples

In one sentence composition in java is used to fulfill the HAS-A relationship. Just imagine one scenario.

John is flying his Helicopter

In the above picture John is flying his own helicopter. So John has a Red two seater helicopter and also John has two hands.

So if I consider John as a class, then two instance variables are like as mentioned below:-

John has two hands and one red colored two seater helicopter

So, Unfortunately , in programming language there are only given few primitive datatypes like int, Double etc. And here we have used the int when we are representing how many hands John have or how many Helicopter he possess. But What about the Helicopter?

How to express in programming term that John has a red , two seater chopper. Because in java they don’t give us any datatype of Helicopter. So we have to define one class of Helicopter. As we all know that class is nothing but “Advanced Datatype”. Those which are not able to express with primitive datatypes can be expressed in terms of class. That’s the beauty of a object oriented programming. So here we are using one instance variable of type Helicopter class. This is composition my friends. When we are using the variables of type class.

See the source image
John also has a big house:-

John is a rich person. He also has a big house. So we have to create one more HAS-A relationship in the John class as shown below.

John has a house also:-

Java Composition Benefits

Main benefit is that it can be represent with more than one class. Which is not possible in case of inheritance in java. Also here the classes are independent to each other.