What is composition in Java?

Asked 14-Nov-2017
Viewed 337 times


What is composition in Java?

1 Answer


'Composition in Java'

The composition is a technique that is used to implement has-a relationship between object. And for reusing the code, you can use java inheritance or object composition.  

In Java, a composition is achieved by using instance variables that pointed to other objects.

public class Employee {
private String name;
private long salary;
private int id;
public String getName() {
return name;
public void setName(String name) {
this.role = name;
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;
public class Person {
//composition has-a relationship
private Employee employee;
public Person(){
this. employee =new employee ();
public long getSalary() {
return employee.getSalary();

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