Tutorial

Composition in Java Example

Published on August 3, 2022
Default avatar

By Pankaj

Composition in Java Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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) {
        this.id = id;
    }
    
    
}
package com.journaldev.composition;

public class Person {

    //composition has-a relationship
    private Job job;
   
    public Person(){
        this.job=new Job();
        job.setSalary(1000L);
    }
    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. https://www.youtube.com/watch?v=VfTiLE3RZds 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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 31, 2019

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

- Bhagyashree Bhuyan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 2, 2019

    What’s back-end class?

    - linjiejun

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 26, 2018

      Hi, 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?

      - Mano

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 12, 2017

        very nice tutorial and thanks for code

        - meghna

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 30, 2016

          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()

          - albert

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 30, 2016

            Thanks for giving information, really very nice post.

            - Genesis Technologies

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 11, 2016

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

              - Sidharth Panda

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 3, 2015

                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.

                - manjusha

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  April 3, 2015

                  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…

                  - manjusha

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    January 4, 2015

                    A relationship defines the connection between objects. This explains how objects are connected to each other’s and how they will behave. Association 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. Aggregation 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. Composition 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. Dependency 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.

                    - anil kumar sahoo

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel