Composition in Java Example

Sythesis in java is the plan strategy to actualize has-a relationship in classes. We can utilize java legacy or Object arrangement in java for code reuse.

Composition in Java

ava arrangement is accomplished by utilizing occasion factors that alludes to different items. For instance, a Person has a Job. We should see this with a java structure model code.

Java Composition Example


package com.journaldev.composition; 

public class Job { 

private String job; 

private long compensation; 

private int id; 

public String getRole() { 

return job; 


public void setRole(String role) { 

this.role = job; 


public long getSalary() { 

return compensation; 


public void setSalary(long salary) { 

this.salary = compensation; 


public int getId() { 

return id; 


public void setId(int id) { = id; 




package com.journaldev.composition; 

public class Person { 

//sythesis has-a relationship 

private Job work; 

public Person(){ 

this.job=new Job(); 



public long getSalary() { 

return job.getSalary(); 



Here is a test class for java creation model that utilizes individual article and get it's salary.

package com.journaldev.composition; public class TestPerson { public static void main(String[] args) { Individual = new Person(); long pay = person.getSalary(); } }

Java Composition Benefits

Notice that above test program for sythesis in java isn't influenced by any adjustment in the Job object. In the event that you are searching for code reuse and the connection between two classes is has-a then you should utilize structure as opposed to inheritance.

Benefit of utilizing organization in java is that we can control the perceivability of other article to customer classes and reuse just what we need.

Likewise if there is any adjustment in the different class execution, for instance getSalary returning String, we have to change Person class to oblige it however customer classes doesn't have to change. Arrangement permits production of back-end class when it's required, for instance we can change Person getSalary technique to introduce the Job object at runtime when required. Further Reading: Do you know a standout amongst the best practice in java writing computer programs is to utilize piece over legacy, look at this post for definite investigation of Composition versus Inheritance. Inheritance in Java

Inheritance in Java is the technique to make a chain of command between classes by acquiring from other classes.

Java Inheritance is transitive – so in the event that Sedan expands Car and Car broadens Vehicle, at that point Sedan is additionally acquired from Vehicle class. The Vehicle turns into the superclass of both Car and Sedan.

Inheritance is broadly utilized in java applications, for instance stretching out Exception class to make an application explicit Exception class that contains more data like mistake codes. For instance NullPointerException<.

© Journaldev Python 3 tutorial spring tutorial