Composition in Java Example

Composition in java is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition in java for code reuse.

Composition in Java

Java composition is achieved by using instance variables that refers to other objects. For example, a Person has a Job. Let’s see this with a java composition example code.

Java Composition Example

Here is a test class for java composition example that uses person object and get it’s salary.

Java Composition Benefits

Notice that above test program for composition in java is not affected by any change in the Job 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.

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

Also if there is any change in the other class implementation, for example getSalary returning String, we need to change Person class to accommodate it but client classes doesn’t need to change.

Composition allows creation of back-end class when it’s needed, for example we can change Person getSalary method to initialize the Job object at runtime when required.

Further Reading: Do you know one of the best practice in java programming is to use composition over inheritance, check out this post for detailed analysis of Composition vs Inheritance.

Java Composition Youtube Video

Recently I created a YouTube video to explain composition in java in detail, please watch it below.

That’s all for composition in java or java composition example. I hope you will find it useful in making informed decision when designing your application classes.

Reference: Wikipedia Page

By admin

Leave a Reply