HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

OOPs-inheritance: What is composition in java?

Please explain with example and where it is used.

OOPs x 49
inheritance x 7
Posted On : 2014-05-18 00:20:48.0
profile Rishi Kumar - Rishi Kumar


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

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) { = id;


public class Person {

//composition has-a relationship
private Job job;

public Person(){
this.job=new Job();
public long getSalary() {
return job.getSalary();


Posted On : 2014-05-18 00:53:52
Satisfied : 1 Yes  0 No
profile Garima Gupta - Garima Gupta
Reply This Thread
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?
profile Ram Tobolski - Ram Tobolski
0  0  0
Posted On :2015-04-15 15:44:04.0
Leave a Comment
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.
profile Garima Gupta - Garima Gupta
596  1295  54552
Posted On :2015-05-11 20:29:27.0
Leave a Comment

Post Answer
Please Login First to Post Answer: Login login with facebook -