Java Composition – What Is Composition (Has-A) In Java

This Java Composition tutorial explains what is Composition and Aggregation in Java and the differences between them:

In the last couple of tutorials, we discussed inheritance in Java in detail. Inheritance in Java is a type of “IS-A” relationship which indicates that one object ‘is a kind of’ another object. For example, a car is a type or kind of vehicle.

Object-oriented programming provides another type of relationship called the “HAS-A” relationship. In this tutorial, we will discuss the has-a relationship in detail.

=> Visit Here To Learn Java From Scratch.

Composition (Has-A) in Java

Java Composition Tutorial

The ‘has-a’ relationship in Java is called Composition. By using ‘has-a’ relationship or composition we ensure code reusability in our programs.

So by making our programs use ‘has-a’ relationship, what we are doing here is that we make our program use an instance of a class directly instead of ‘extending’ it from another class as we do in case of inheritance.

The below diagram depicts both ‘is-a’ and ‘has-a’ relationships in Java.

Has - A Relation

As seen from the above diagram, Car and Vehicle share the ‘IS-A’ relationship as a car is a vehicle. Hence we create a car object from the existing vehicle object by adding more characteristics to it.

In the diagram, Car and Engine share the ‘Has-a’ relationship. A car always has an Engine. So what we do here is that we do not extend the properties of the Engine object but we use the Engine object directly. This is done in Java using composition.

Hence along with encapsulation, abstraction, and polymorphism, inheritance and composition are also important features of Object-oriented programming (OOP).

The ‘has-a’ relationships usually determine if a certain object has another object. So what we do here is we reuse an object and thus reduce code duplication as well as errors. This is because we use a completely developed and tested object in our class.

Let’s start with the discussion of a special relation called “Association” in Java from which we derive composition and other relationships.

Association In Java

Association in Java can be defined as a relation that exists between two individual classes using their separate objects. Association in Java can have the following relationships.

  • One-to-one: One object associated with exactly one object.
  • One-to-many: One object can be associated with many objects.
  • Many-to-one: Many objects can be associated with one object.
  • Many-to-many: More than one object associated with more than one other object.

When a relationship is established, the containing objects (objects that have other objects as their members) communicate with the contained object to reuse their properties and characteristics. Association has two forms i.e.  Composition and Aggregation.

The below figure shows this:

Composition and Aggregation

As seen from the above diagram, the Association includes Composition and aggregation. Composition is a more specific term and aggregation is more general than composition. These forms are based on what type of relationships they support.

Before we move on to Composition and Aggregation, let’s implement a Java program to demonstrate the Association in Java.

// class Account  
class Account  { 
    private String bank_name; 
    private long Account_number;
    // initialize bank name and account number
    Account(String bank_name, long Account_number)   { 
        this.bank_name = bank_name; 
        this.Account_number = Account_number;
    //read bank name 
public String getBankName() { 
   //read account number
public long getAccountNumber() {
// employee class  
class Employee 
    private String emp_name; 
    // initialize employee name  
    Employee(String emp_name)  
        this.emp_name = emp_name; 
    //read employee name  
    public String getEmployeeName() 
        return this.emp_name; 
// Associate both the classes 
class Main  
    public static void main (String[] args)  
        Employee emp = new Employee("Andrew"); 
        Account acc = new Account("Citi Bank", 13319); 
        System.out.println(emp.getEmployeeName() +  
               " has an account with " + acc.getBankName() + " with Account Number:"
               + acc.getAccountNumber()); 


Association Ex Output

The above program demonstrates an association in Java. Here, we have a class Account that has a bank name and account number as private members. Next, we have an Employee class. We know that every employee will have an account number for depositing salary etc.

So what we do is, instead of writing another class or method to read in the Employee’s bank account details, we directly reuse the existing Account class. In other words, we associate an Account object with the Employee so that we get the Employee’s bank account details. The above example exactly does this.

Composition In Java

The composition is one form of Association. The composition can be defined as an association in which one class contains another class and this contained class depends on the containing class in such a way that it cannot exist independently.

We have seen an example of a has-a relationship above. In that, we had a car object which has an engine. This is an example of composition. In this, an engine cannot exist independently without a car.

The composition is more restricted when compared to Aggregation. The composition is not a Java feature. It is mainly considered a design technique.

The following diagram shows a composition example.

composition example

In this, an Employee has a bank account. We know that a bank account cannot exist without an account holder. Without an account holder, it becomes dormant.

We can use composition to model objects which have other objects as its members and these objects have ‘has-a’ relationship between themselves.

In composition, an object is contained in another object, hence when the containing object is destroyed; the other object is also destroyed

So we can view the composition relationship as a “part-of-a-whole” relationship in which the part does not exist without the whole. Hence, when the whole is destroyed, the part is deleted as well. This means that the whole has a stronger relationship with the part.

Java Composition Example

Given below is the program to demonstrate composition.

The system we used here is represented as below.

Composition example

So in this program, we have three classes as shown above. Honda is a Car so it extends from the class Car. CarEngine Object is used in Honda class.

The program is given below.

class CarEngine {
	public void startEngine(){
		System.out.println("Car Engine Started.");
	public void stopEngine(){
		System.out.println("Car Engine Stopped.");

class Car {
	private String color;
	private int max_Speed; 
	public void carDetails(){
		System.out.println("Car Color= "+color + "; Max Speed= " + max_Speed);
	//set car color
	public void setColor(String color) {
		this.color = color;
	//set car max_Speed
	public void setMaxSpeed(int max_Speed) {
		this.max_Speed = max_Speed;

class Honda extends Car{
	public void HondaStart(){
		CarEngine Honda_Engine = new CarEngine();   //composition

public class Main {
	public static void main(String[] args) {		
		Honda HondaCity = new Honda();


Output - Composition Example

Thus the output shows the properties of Honda cars. It also shows the output of a method from the CarEngine class that we have used as a member of the Honda class using composition.

This program showed how we can use composition in a Java program.

Aggregation In Java

Aggregation is another form of association in Java. But in the case of aggregation, it only allows the one-way relationship between the objects. For example, an employee has a home address. But vice versa, the home address has employees, doesn’t sound right.

Similarly, a student has an address but “address has a student” doesn’t make sense. Like composition, aggregation also depicts the “has-a” relationship. This means a class contains an object of another class.

The below diagram represents an Aggregation example.

Aggregation Example

The above example can be interpreted as the College has staff and students.

So when exactly should we go for Aggregation?

We should use aggregation when there is no need to use an “is-a” relationship or inheritance. If we can maintain the ‘is-a’ relationship throughout the application or lifetime of an object, then we can implement inheritance for code reuse.

Otherwise, it is best to use aggregation for code reusability. Let’s now implement an example aggregation in Java.

The example system we have used is as follows:

example aggregation

Here we have an ‘Institute’ class. Institute can have various departments or branches. Each branch in turn has several students. In this program, we will count the total number of students in the entire institute. We use aggregation for this purpose. The class Institute contains the Branch object.

The branch object has a student object. So in the Institute class using the Branch object we count the total number of students. For this purpose, we use a list of branches in an institute.

The Java program is given below.

import java.util.*; 
// Class Student 
class Student  
    String student_name; 
    int student_id ; 
    String student_dept; 
    //Initialize Student class members  
    Student(String student_name, int student_id, String student_dept)  
        this.student_name = student_name; 
        this.student_id = student_id; 
        this.student_dept = student_dept; 
//Branch class indiates the branch or department to which the student belongs 
class Branch  
    String Branch_name; 
    private List<Student> students; //Each branch contain students
    //Initialize class members   
    Branch(String Branch_name, List<Student> students)    { 
        this.Branch_name = Branch_name; 
        this.students = students; 
    //return list of students  
    public List<Student> getStudents()  
        return students; 
//Institure class contains branches which in turn have students
class Institute  {       
    String instituteName; 
    private List<Branch> branches;  //each institure have various branches
    //initialize members  
    Institute(String instituteName, List<Branch> branches)   { 
        this.instituteName = instituteName; 
        this.branches = branches; 
    // count and return number of all students in the institute  
    public int getAllStudentsInInstitute()   { 
        int noOfStudents = 0; 
        List<Student> students;  
        for(Branch branch : branches) 
            students = branch.getStudents(); 
            for(Student s : students) 
        return noOfStudents; 
//Aggregate all the classes=> Institute (contains) branches (contains) Students
class Main 
    public static void main (String[] args)  
        //declare student objects
        Student s1 = new Student("Megan", 1, "CSE"); 
        Student s2 = new Student("Mia", 2, "CSE"); 
        Student s3 = new Student("John", 1, "ETC"); 
        Student s4 = new Student("Finn", 2, "ETC"); 
        // List of CSE Students. 
        List <Student> cse_students = new ArrayList<Student>(); 
        //List of ETC Students 
        List <Student> etc_students = new ArrayList<Student>(); 
        //declare Branch objects  
        Branch CSE = new Branch("CSE", cse_students); 
        Branch ETC = new Branch("ETC", etc_students); 
        //make list of branches  
        List <Branch> branches = new ArrayList<Branch>(); 
        // creating an object of Institute. 
        Institute institute = new Institute("NIT", branches); 
        //display total number of students  
        System.out.print("Total students in NIT institute: "); 


Aggregation in Java - Output

Hence aggregation and composition are two forms of association that we have discussed here. When we do not need or cannot represent ‘is-a’ relationship between objects then we can go for composition if we want a stronger relationship between objects or aggregation if we want a one-way relationship.

Both aggregation and composition help us to reuse code in Java.

Differences Between Aggregation Vs Composition

Both Composition and Aggregation are parts of the Association that depicts a ‘has-a’ relationship. Both the techniques are not Java features and do not have a direct way to implement but can be implemented using Java code.

Composition and Aggregation allow us to reuse the code. Code reusability reduces the bugs in the code and also makes the application more stable.

Enlisted below are some differences between Aggregation and Composition.

Aggregation allows child objects or contained objects to exist independently. For example in a relationship where School has Employees, if we delete School, Employees will remain and can function on its own.In composition, the contained object cannot exist independently. For example a car has Engine. If we delete Car, Engine class cannot function on its own.
Aggregation is a ‘has-a’ relationship.The composition is a form of ‘has-a’ relationship but viewed as part-of-a-whole’ relation.
The aggregation has one to one association only.Composition allows other relationships provided in the association.
The aggregation has a weak association between objects.The composition has a strong association between objects.

Composition Vs. Inheritance

The composition depicts the ‘Has-A’ relationship.Inheritance represents ‘Is-A’ relationship.
Easier to change the implementation of containing objects.When one implementation changes the entire hierarchy of inheritance changes.
Has a dynamic or run time-binding.Has a static or compile time binding.
The Front-end class interface can be changed easily without impacting the back-end classes. Any changes in methods or prototypes affect all classes.
The composition is used when we do not need to add more characteristics or features to an existing object.Inheritance is used when more features are to be added to inherited classes.

Frequently Asked Questions

Q #1) What is the difference between ‘IS – A’ and ‘HAS – A’ relationship?

Answer: In Object-oriented programming, IS-A relations represent inheritance in which a child class ‘is a kind of’ a parent class. The Has-a relationship is a ‘part-of-a – whole’ relationship which is represented by composition and aggregation. Inheritance is a static binding while Composition is dynamic binding.

Q #2) What is Aggregation and Composition in Java?

Answer: In Composition, the two objects are tightly coupled i.e. when the object (Containing object) that owns another object (contained object) is destroyed, then the other object is automatically destroyed as it cannot function independently on its own.

In Aggregation, the containing and the contained object can function independently. This is because, in Aggregation, one object uses another object.

Q #3) Why do we use Composition in Java?

Answer: Composition allows us to reuse the existing code thereby reducing the code complexity and also reduces the bugs in the code. Using composition we can reuse only what we need from the object and also control its visibility.

Q #4) What is the use of Association?

Answer: Association represents the ‘has-a’ relationship in Java. Association in Java is used when one object needs to use the functionality and services of another object. Composition and aggregation are two forms of association.

Q #5) Is Composition better than Inheritance?

Answer: It depends on the OOP system that we are coding. If we can represent the objects with IS-A relationship throughout its lifetime in the application then inheritance is a better option. When we want to reuse the code and cannot represent the object system with the IS-A relationship then the composition is better.

Also, when we want to frequently change front-end classes without disturbing the back-end classes, then the composition is better because in the case of inheritance slight changes mostly affect the entire inheritance hierarchy.


In this tutorial, we have discussed the HAS-A relationship in Java. Composition and aggregation are the forms that implement the ‘HAS-A’ relationship. We have compared both these implementations.

While both contain objects of another class, composition owns the object while aggregation simply uses the object. We have also compared the composition and inheritance in Java.

=> Check Here To See A-Z Of Java Training Tutorials.