Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconWhat is Composition in Java With Examples

What is Composition in Java With Examples

Last updated:
19th Feb, 2024
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
What is Composition in Java With Examples

Java is a versatile language that supports object-oriented programming and code reusability with building relationships between two classes. There are two types of relationships or associations in Java used to reuse a code and reduce duplicity from one class to another.

These relationships are IS-A(Inheritance) and HAS-A (Association). While there is a tight coupling between the IS-A classes, HAS-A classes are loosely coupled and more preferable for the programmers.

The HAS-A relationship is divided into two types, viz., aggregation and composition in Java. This article is based on the OOP concept of composition. We will see many real-life examples of how the composition is coded and the advantages gained when implemented.

Check out our free courses related to software development.

Ads of upGrad blog

Explore Our Software Development Free Courses

A Brief Narration of Associations or Relationships in Java

In object-oriented programming, objects are related to each other and use the common functionality between them. This is where the topics of Inheritance, Association, Aggregation, and Composition in Java programs come.

 Inheritance (IS-A) and Association (HAS-A) in Java

Check Out upGrad’s Java Bootcamp

1. Inheritance (IS-A)

An IS-A relationship signifies that one object is a type of another. It is implemented using ‘extends’ and ‘implements’ keywords.

Example: HP IS-A laptop

Our learners also read: Learn java online free!

2. Association (HAS-A)

A HAS-A relationship signifies that a class has a relationship with another class. For instance, Class A holds Class B’s reference and can access all properties of class B.

Example: Human body HAS-A Heart




3. Aggregation Vs Composition

Has-A relationship or Association can be divided into aggregation and composition. An aggregation container class and referenced class can have an independent existence. A composition reference class cannot exist if the container class is destroyed.

Check Out upGrad’s Advanced Certification in Blockchain  

Let’s take an example to understand aggregation and composition. A car has its parts e.g., engines, wheels, music player, etc. The car cannot function without an engine and wheels but can function without a music player. Here the engine and car have a composition relation, and the car and music player have an aggregation relationship. In the case of Aggregation, an object can exist without being part of the main object.

DefinitionAggregation represents a “has-a” relationship where one class contains a reference to another class. It’s like saying a car has wheels.Composition is a stricter form of aggregation where one class owns another class, meaning the contained class’s existence is dependent on the container. It’s like saying a car has an engine.
DependencyIn aggregation, the contained class can exist independently of the container class. If the container is destroyed, the contained class can still exist.In composition, the contained class’s lifecycle is tied to the container. If the container is destroyed, the contained class is also destroyed.
FlexibilityAggregation is more flexible as it allows the contained class to be shared among multiple containers.Composition is less flexible because the contained class is exclusive to its container and cannot be shared.
RelationshipAggregation signifies a weaker relationship between classes. The contained class can belong to multiple containers simultaneously.Composition signifies a stronger relationship where the contained class is part of the container and cannot be associated with any other container.
ExamplesAn example of aggregation is a university having departments. Departments can exist independently of the university and can belong to multiple universities.An example of composition is a car having an engine. The engine is an integral part of the car and cannot exist without it.

Composition Vs. Inheritance


DefinitionComposition involves creating complex objects by combining simpler ones, composition in oopsInheritance is a mechanism where a new class is derived from an existing class.
RelationshipThe relationship between objects is “has-a.”The relationship between objects is “is-a.”
FlexibilityOffers more flexibility as it allows changing the parts of the object independently.Less flexible because changes to the base class can affect all derived classes.
Code ReusabilityPromotes code reuse by allowing the use of existing classes without being tied to their implementation details.Code reuse is facilitated through the extension of existing classes.
ComplexityTypically leads to simpler, more modular code.Can lead to complex class hierarchies, which might be harder to understand.
DependencyObjects can exist independently of each other.Dependent on the base class, changes to which can affect derived classes.
EncapsulationEncourages encapsulation as objects hide their internal details.May violate encapsulation as derived classes have access to all members of the base class.



Composition in Java

A composition in Java between two objects associated with each other exists when there is a strong relationship between one class and another. Other classes cannot exist without the owner or parent class. For example, A ‘Human’ class is a composition of Heart and lungs. When the human object dies, nobody parts exist.

The composition is a restricted form of Aggregation. In Composition, one class includes another class and is dependent on it so that it cannot functionally exist without another class.

In-Demand Software Development Skills

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?


Implementation of Composition in Java

The engine and car relationship are implemented using Java classes as below. In Java, the ‘final’ keyword is used to represent Composition. This is because the ‘Owner’ object expects a part object to be available and function by making it ‘final’.

public class Car {

           private final Engine engine; 

    public Car(){

    engine  = new Engine();



 class Engine {

private String type;


Let us take another example that depicts both inheritance and composition.


In this program, the class Honda is a Car and extends from the class Car. The car engine Object is used in the Honda class.

class CarEngine {

    public void StartEngine(){

        System.out.println(“The car engine has Started.”);


    public void stopEngine(){

        System.out.println(“The car engine has Stopped.”);


class Car {

    private String colour;

    private int maxi_Speed;

    public void carDetails(){

        System.out.println(“Car Colour= “+colour + “; Maximum Speed= ” + maxi_Speed);


    //Setting colour of the car

    public void setColour(String colour) {

        this.colour = colour;


    //Setting maximum car Speed

    public void setMaxiSpeed(int maxi_Speed) {

        this.maxi_Speed = maxi_Speed;


class Honda extends Car{

    public void HondaStart(){

        CarEngine Honda_Engine = new CarEngine(); //composition



public class Main {

    public static void main(String[] args) {   

        Honda HondaJazz = new Honda();








Car Colour = Black; Maximum Speed = 160

The car engine has started. 

The output is derived using composition and shows the details of the Honda Jazz car.

Explore our Popular Software Engineering Courses

UML Denotations of Association

The relationships of association, aggregation, and composition in Java between classes A and B are represented as follows in UML diagrams:

Association: A—->B

Composition: A—–<filled>B

Aggregation: A—–<>B

Get Software Engineering degrees online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Learn Java Tutorials

Benefits of Composition in Java

Using composition design technique in Java offers the following benefits:

  1. It is always feasible to “prefer object composition over class inheritance”. Classes achieve polymorphism and code reuse by composition.
  2. The composition is flexible, where you can change class implementation at run-time by changing the included object, and change its behaviour.
  3. A composition-based design has a lesser number of classes.
  4. THE “HAS-A” relationship between classes is semantically correct than the “IS-A” relationship.
  5. Composition in Java offers better class testability that is especially useful in test-driven development.
  6. It is possible to achieve “multiple inheritances” in languages by composing multiple objects into one.
  7. In composition, there is no conflict between methods or property names.

Check out all trending Java Tutorials in 2024. 

Features of Composition in Java

Composition is a fundamental concept in Java programming that enables the creation of complex objects by combining simpler ones along with description, what is composition in java with example.  It facilitates code reuse, maintainability, and flexibility in designing software applications. Let’s explore the key features of composition in Java:

  • Object Composition

Object composition involves creating complex objects by combining simpler ones. In Java, this is achieved by defining classes that contain references to other classes as instance variables. This allows objects to be composed of other objects, forming a hierarchical structure.

  • Has-a Relationship

Composition establishes a “has-a” relationship between classes, where one class contains objects of another class. This relationship signifies that a class has references to other classes to fulfill its functionality. For example, a Car class may have instances of Engine, Wheels, and Seats classes and understanding what is composition in java.

  • Code Reusability

Composition promotes code reusability by allowing the reuse of existing classes within new classes. Instead of inheriting behavior through inheritance, classes can reuse functionality by containing instances of other classes. This enhances modularity and reduces code duplication, composition example in java.

  • Encapsulation

Encapsulation is maintained through composition as the internal details of the composed objects are hidden from the outside world. Each class manages its own state and behavior, providing a clear separation of concerns. This enhances code maintainability and reduces the risk of unintended side effects and composition writing examples.

  • Flexibility and Modifiability

Composition offers greater flexibility compared to inheritance, as it allows classes to change behavior dynamically by replacing or modifying the objects they contain. This promotes a modular design approach, where individual components can be modified or extended without affecting the entire system.

  • Dynamic Behavior

With composition, the behavior of an object can be dynamically changed at runtime by replacing its constituent objects. This dynamic composition enables the creation of highly adaptable and customizable systems, where different configurations of objects can be used to achieve varying functionality, with an understanding of aggregation and composition in java.

  • Loose Coupling

Composition helps in achieving loose coupling between classes, as objects are accessed through interfaces rather than concrete implementations. This reduces dependencies between classes and promotes better code maintainability and testability.

  • Granular Control

With composition, developers have granular control over the behavior and state of objects. They can selectively expose certain functionalities of composed objects while encapsulating others, providing a clear interface for interaction with the object, like composition in java.

Benefits of Composition in Java

  • Encapsulation and Modularity

Composition promotes encapsulation, which is the practice of bundling data and methods that operate on that data within a single unit, with an understanding of object composition in java. By encapsulating related functionalities into separate classes, you can create modular and reusable components. This modularity enhances code organization and makes it easier to understand, maintain, and extend, with examples of composition.

  • Code Reusability

One of the primary benefits of composition is code reusability. Instead of inheriting behaviors from a single parent class, you can compose objects by combining multiple classes to achieve the desired functionality. This approach allows you to reuse existing classes in different contexts, reducing code duplication and promoting a more efficient development process.

  • Flexibility and Loose Coupling

Composition promotes loose coupling between classes, which means that the components of a system are independent and can be modified or replaced without affecting other parts of the codebase. This flexibility is essential for building scalable and maintainable applications, as it enables developers to make changes to one part of the system without impacting the entire application.

  • Better Control over Behavior

With composition, you have finer control over the behavior of your objects compared to inheritance. Instead of inheriting all the characteristics of a parent class, you can selectively choose which functionalities to include in a class by composing it with the appropriate components. This granularity allows you to design classes that are tailored to specific requirements, leading to cleaner and more efficient code.

  • Avoiding the Diamond Problem

Inheritance can result in the “diamond problem,” where ambiguity rises when a class inherits from any two or more classes that have an ancestor. Composition helps avoid this issue by allowing you to combine functionalities from multiple classes without creating complex inheritance hierarchies. This simplifies the design and prevents potential conflicts that may arise from multiple inheritance.

  • Facilitates Testing and Debugging

Composition facilitates unit testing and debugging by enabling you to isolate and test individual components independently. Since each class encapsulates a specific set of functionalities, you can easily mock dependencies and simulate different scenarios during testing. Additionally, debugging becomes more manageable as the codebase is divided into smaller, more focused units.

When to Use Composition in Java?

In Java programming, composition is a powerful concept used to build complex objects by combining simpler ones. It involves creating objects by incorporating other objects within them. Knowing when to utilize composition is essential for writing clean, maintainable, and efficient code, with various composition writing sample.

Understanding Composition

Composition establishes a “has-a” relationship between classes, where one class contains another as a part of its state. This is different from inheritance, which establishes an “is-a” relationship. In composition, the contained object does not inherit behavior from the containing class but rather is used to provide functionality or data, with english composition examples.

Encapsulation and Code Reusability

One of the primary use cases for composition is encapsulating functionality. By breaking down complex systems into smaller, more manageable components, you can encapsulate related functionality within separate classes. This promotes code reusability and modular design, making your codebase easier to understand and maintain.

Flexibility and Modifiability

Composition allows for greater flexibility in software design. Since objects are composed of other objects, you can easily modify or replace components without affecting the entire system. This modular approach simplifies testing and debugging and enables you to adapt your code to changing requirements more efficiently when association aggregation and composition in java.

Preventing Tight Coupling

Using composition helps avoid tight coupling between classes, which can make code brittle and difficult to maintain. By relying on interfaces or abstract classes, you can decouple components, making them interchangeable and reducing dependency on specific implementations. This enhances the scalability and extensibility of your codebase.

Promoting Single Responsibility Principle

Composition encourages adhering to the Single Responsibility Principle (SRP), which states that a class should have only one reason to change. By breaking down functionality into smaller, focused classes, each responsible for a specific task, you can create more cohesive and understandable code. This improves code maintainability and reduces the risk of introducing bugs when making modifications.

Example: GUI Components

Consider a graphical user interface (GUI) framework where various components such as buttons, text fields, and panels are composed to create complex interfaces. Each component encapsulates its behavior and appearance, allowing developers to mix and match them to design diverse user interfaces efficiently.


Composition in Java offers many advantages while programming and is one of the favoured design methods. In this article, we have tried to make you understand this important concept with real-life examples and practical code. Composition offers flexibility and robust code. Its code reusability feature helps in avoiding code duplication and achieving cost-effectiveness. This makes it one of the widely used methods in various programs. 

Learn composition in Java with upGrad’s Master of Science in a Computer Science course which is aimed to make you learn and upgrade your skills in software development.


Ads of upGrad blog

A Bachelor’s Degree with 50% or equivalent marks. No initial coding experience is needed.


The program fee starts at Rs.13, 095/month for Indian Residents and USD 5999 for International residents.


Arjun Mathur

Blog Author
Arjun is Program marketing manager at UpGrad for the Software development program. Prior to UpGrad, he was a part of the French ride-sharing unicorn "BlaBlaCar" in India. He is a B.Tech in Computers Science from IIT Delhi and loves writing about technology.

Frequently Asked Questions (FAQs)

1Why is multiple inheritance not supported in Java?

Multiple Inheritance refers to the feature of Java where it can gain features from more than one parent class or object. In Java, one class cannot be extended to more than one. Nevertheless, a class can carry out more than one interface which has assisted Java in removing the impossibility of multiple interferences. The rationale behind this is to prevent ambiguity. For instance, assume a situation where Class D extends class C and Class B and both these classes have the same method display. In this case, the Java compiler can't contemplate which method display to decipher. Thus, to avoid this multiple inheritances aren't supported in Java.

2What is the difference between Aggregation and Association?

Aggregation refers to a 'has a' connection between two related objects. For instance, a department maintains multiple employees. Association refers to a 'has a' connection between two related objects. For instance, an employee possessing a communication address. Aggregation is highly flexible in nature whereas the association is inflexible. Association requires linkages to be mandatory whereas aggregation doesn't require linkages to be mandatory between objects. When we consider UML, the lines are used to represent association whereas in aggregation the diamond shape next to the assembly class depicts the aggregation relationship.

3What is the difference between Inheritance and Encapsulation?

Inheritance is defined as the mechanism through which you can acquire the properties and behaviour of a class into another class. Encapsulation is the winding of data into a single unit which is known as class. Inheritance implies that a child class inherits the attributes from the parent class whereas encapsulation implies that a particular class should not have access to the private data of another class. In encapsulation, we should focus on what should be exposed in a class and what should not be exposed. When discussing the class, the decision should be based on data and behaviour.