What is JAVA Composition?

In inheritance, we create a sub class of the master class in order to extends its functionality and properties.Inheritance enables the code reuse and increase the developers productivity. Inheritance provides tight coupling between super class and sub class.

Composition is another way in which a specific relationship between two independent class is created. Composition uses HAS-A relationship between two classes. For example if we have two classes like human and cow. A cow HAS A relationship with a human. i.e its owner. Similarly Car HAS A engine, A department HAS A employee. Employee HAS A salary. Composition is achieved through declaring instance variables of type other class. It also provide the advantage of code reuse, hides internal functionality of other class and increase the developer productivity. Composition also provides lose coupling between the two related classes.

Below example illustrate the concept of a composition


   Output of the program is as below:





In above example two separate classes are created which then connected through composition showing the relationship between the two classes. These classes are also independent of each other.
Employee class only uses one property of the Salary i.e. empsalary.