Composition in Java Example

Filed Under: Java

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

composition in java, java composition, java composition example

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

package com.journaldev.composition;

public class Job {
    private String role;
    private long salary;
    private int id;
    public String getRole() {
        return role;
    public void setRole(String role) {
        this.role = role;
    public long getSalary() {
        return salary;
    public void setSalary(long salary) {
        this.salary = salary;
    public int getId() {
        return id;
    public void setId(int id) { = id;

package com.journaldev.composition;

public class Person {

    //composition has-a relationship
    private Job job;
    public Person(){
        this.job=new Job();
    public long getSalary() {
        return job.getSalary();


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

package com.journaldev.composition;

public class TestPerson {

    public static void main(String[] args) {
        Person person = new Person();
        long salary = person.getSalary();


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


  1. Bhagyashree Bhuyan says:

    getSalary() methods’s return type is long here , why it is mentioned above as String

  2. linjiejun says:

    What’s back-end class?

    1. Henry says:

      This are classes that refer to the server side of the application. They help to connect the application to the servers.

  3. Mano says:

    Inheritance and composition are establishing their relationship in different ways. Inheritance will establish is-a and composition will establish has-a relationship. I couldn’t relate these on favoring composition over inheritance. We can say person is a user and person has a job. We can’t compose user with person and we can’t extend job to person. Then why we are favoring composition over inheritance?

    1. DMC says:

      Usually we said that Inheritance can break the encapsulation, but Composition there is no chance to break the encapsulation
      Why composition cant break the encapsulation ??

  4. meghna says:

    very nice tutorial and thanks for code

  5. albert says:

    You should not create the Job object in the Person constructor. You should create elsewhere and inject it after. Either create a constructor that takes Job as parameter (I would not do that either) or even better create setJob getJob methods to return the job. Also the the person.getSalary() is wrong in my opinion, It should be person.getJob().getSalary()

    1. Hoang Tu says:

      I add println() method, test it in main(char[] args) and it works (the output platform show exactly what is in job.setSalary() ). I think its no problem here.

      1. Shirish herwade says:

        Composition is not “has-a” relationship. Instead it is “part-of” relationship e.g. human and heart where heart can’t be present without human. And aggregation is “has-a” relationship e.g. bank and employee where without bank there is still presence of employee. And these two(Aggregation and Composition are types of association)

    2. sohail Ahmad says:

      bro you are talking about Aggregation

  6. Genesis Technologies says:

    Thanks for giving information, really very nice post.

  7. Sidharth Panda says:

    Some examples code perspective regarding to Association,Aggregation & Composition would be much more helpful . Please share some code snippets regarding this

  8. manjusha says:

    here, we need to change the client class i.e. person also as we are going to change the salary type to String and here it’s type is long.

    1. manjusha says:

      sorry.. we need to change TestPerson also.

  9. manjusha says:

    here we need to change the person as well, because your assigning the salary value to long type, and your going to change it’s type to String..

  10. anil kumar sahoo says:

    A relationship defines the connection between objects. This explains how objects are connected to each other’s and how they will behave.
    It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.

    Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.

    It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.

    Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.

    It is a specialized form of Aggregation. It is a strong type of Aggregation. In this relationship child objects does not have their lifecycle without Parent object. If a parent object is deleted, all its child objects will also be deleted. This represents “death” relationship. This is represented by a solid diamond followed by a line.

    Let’s take an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete.

    Let’s take another example of relationship between Questions and options. Single questions can have multiple options and option cannot belong to multiple questions. If we delete questions options will be automatically deleted.
    It represents a relationship between two or more objects where an object is dependent on another object(s) for its specification or implementation. This is represented by a dashed arrow.

    Let’s take an example of relationship between client and service. A client is dependent on the service for implementing its functionalities.

    Let’s take another example of relationship between a client and a supplier. A client is dependent on the supplier for supplying products. If the supplier will not supply the products, client cannot use those products.

    1. Siddharth says:

      can you put more light on how we can use it in list elemnts
      like a employee has-a address..

    2. sanjok khakurel says:

      i am a student of computer science ,i am in the final year ,i have been learning java since1 year ago ,

      your explanation just boosted my curiosity , so i could not stay without asking you some example implementing those relationship .

      it would be trillion droller help for people like me if you could provide example implementing those relationship !

    3. Raju B says:

      Yes anil ur right here concept is relationship but all are thinking about return.

  11. ibrar khan says:

    what is the difference between inheritance and polymorphism?

  12. Fahim says:

    This code is not going to return salary, IS IT?

    1. Michael says:

      just add ” System.out.println(salary);” , it will prints the value.

  13. Farrukh says:

    Hi, what is the difference between aggregation and composition ?

    1. Barkulhan bulgan says:

      They aren’t different. Composition is a special kind of aggregation.

  14. manoj says:

    To have more clarity on Why composition should be favored over inheritance, Please read

  15. Vishv Deepak says:

    what is class composition in it differ from object composition.

  16. srini says:

    is there a concept of aggregation(weak) and composition in Javs similar in lines to C++.

    1. Pankaj says:

      Java has concept of aggregation and composition, read about composition in java.

      1. Joselito A. Gamao Jr. says:

        Is it possible to use super?

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content