top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is Composition in JAVA?

+1 vote
301 views
What is Composition in JAVA?
posted Mar 25, 2014 by Neeraj Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Composition is the design technique to implement has-a relationship in classes. 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 simple code.

Job.java

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;
    }
}

Person.java

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 that uses person object and get it’s salary.

TestPerson.java

package com.journaldev.composition;

public class TestPerson {

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

Notice that above test program 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 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.

Credit: http://www.journaldev.com/1325/what-is-composition-in-java-java-composition-example

answer Mar 26, 2014 by Salil Agrawal
...