What is composition in Java?

1 votes
102 views
Siris Jain asked 14-Nov-2017 in programming by Siris Jain

What is composition in Java?

1 Answer

0 votes
Arti Mishra answered 12-Jul-2018 by Arti Mishra

"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.
'

Employee.java
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;
}
Person.java
public class Person {
//composition has-a relationship
private Employee employee;
public Person(){
this. employee =new employee ();
employee.setName(“ABCD”);
}
public long getSalary() {
return employee.getSalary();
}
}

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