Composition is a technique to implement has-a relationship between classes. We can use java inheritance or Object composition to make our code reusable. Java composition is implemented by using instance variables that refers to other objects. Let´s consider an example in which two classes named Job and Person. Person has the reference of the Job class(We can say that Each person had a job):
Job.java:
-----------------
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:
---------------------
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();
}
}
5
Hello. If I understood correctly, the consequence of using an instance variable is dependence, in the sense that a Job instance is created, and destroyed, together with the Person instance. This may not be ideal, because a Job may be independent of a specific Person (the same Job may be filled by another Person). What do you think?
Yes. Job may be independent of a specific person but it is occupied by someone. So all person has their job. So person class has its reference. We are not talking about any specific person or specific job.