Blog_Banner_Asset
    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:
9th Apr, 2021
Views
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

Source

 

Source

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.

 

Source

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.

Source 

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

        Honda_Engine.startEngine();

        }

public class Main {

    public static void main(String[] args) {   

        Honda HondaJazz = new Honda();

        HondaJazz.setColour(“Black”);

        HondaJazz.setMaxSpeed(160);

        HondaJazz.carDetails();

        HondaJazz.HondaStart();

    }

}

Output:

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.

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.

Read our Popular Articles related to Software Development

Conclusion

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.

Eligibility

Ads of upGrad blog

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

Pricing

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

Profile

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.

Explore Free Courses

Suggested Blogs

DevOps Engineer Salary in India in 2023 [For Freshers &#038; Experienced]
901764
Wondering what is the range of DevOps Salary in India? In the last few years, DevOps has evolved from being just a “buzzword” to a mainstream practic
Read More

by upGrad

07 Nov 2023

What Is AWS Route 53 and How Does It Work?
1298
Managing domain names and directing traffic efficiently is pivotal in the intricate web of cloud computing and web hosting. Enter AWS Route 53, Amazon
Read More

by Pavan Vadapalli

29 Sep 2023

Agile vs Scrum: Difference Between Agile and Scrum
2046
Keeping up with the fast-paced nature of project development fueled by technological progress is challenging, to say the least. To function efficientl
Read More

by Pavan Vadapalli

28 Sep 2023

What Is Azure Active Directory? A Complete Guide
1301
In the ever-evolving landscape of cloud computing, Azure Active Directory or Azure AD has emerged as a cornerstone in identity and access management.
Read More

by Pavan Vadapalli

28 Sep 2023

Difference Between Product Backlog and Sprint Backlog: A Quick Guide
1249
Agile is a highly effective project management methodology, but its efficiency relies on the team’s collective understanding of key concepts, su
Read More

by Pavan Vadapalli

28 Sep 2023

Agile Manifesto Explained: Understanding Agile Values
1683
Manifestos are formal declarations of principles or beliefs that guide movements or ideologies. The impact of the Agile Manifesto principles has exten
Read More

by Pavan Vadapalli

28 Sep 2023

Top 22 Best Agile Project Management Tools in 2023
1469
The recent years have seen a surge in using the best Agile management tools and techniques, especially in software development. Breaking down projects
Read More

by Pavan Vadapalli

27 Sep 2023

Scrum Master Roles and Responsibilities: Everything You Should Know
1825
In today’s fast-paced business environment, organisations constantly seek ways to enhance their productivity, collaboration, and product quality
Read More

by Pavan Vadapalli

27 Sep 2023

What Is Programming Language? Syntax, Top Languages, Examples
1739
Computer programming is expanding daily, with new programming languages being launched yearly, adding to the list.  Renowned companies now look for co
Read More

by Pavan Vadapalli

25 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon