Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconWhat is Composition in Java with Examples

What is Composition in Java with Examples

Last updated:
18th Nov, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
What is Composition in Java with Examples

The versatility of the Java programming language allows code reuse while reducing duplicity between classes. Java facilitates code reusability by building relationships between classes, and these relationships are of two types: inheritance and association. While inheritance lets us implement an is-a relationship and create a new class from an existing class, association or has-a relationship ensures code reusability. 

The has-a relationship is further divided into two categories: aggregation and composition in Java. This article will explore the concept of composition in Java and help you understand its fundamentals with examples.

An Overview of Relationships in Java

Relationships in Java refer to the different ways classes are related. Broadly, there are two types of relationships in Java:

  • Is-a relationship
  • Has-a relationship

Composition in Java

Ads of upGrad blog

Source

Is-a relationship (Inheritance)

The inheritance feature in Java lets us implement is-a relationships. In this case, one class inherits another class. For instance, if a class ‘Flower’ inherits another class, ‘Lily,’ we can say that class ‘Lily’ has an is-a relationship with ‘Flower.’ It also implies that Lily is a flower.

Example: Lily ‘is a’ flower, computer ‘is a’ device, and so on.  

Has-a relationship (Association)

A has-a relationship signifies that a class uses the instance of another class, and such a relationship in Java is called association. For example, if a class P holds another class Q’s reference, it implies that P can access all properties of class Q. 

Example: Computer ‘has a’ processor, bee ‘has a’ sting, etc. 

An association in Java is a relationship between two discrete classes using their objects. The relationship can be of the following types:

  • One-to-many: One object associates with multiple objects.
  • One-to-one: One object associates with a single object.
  • Many-to-many: Many objects associate with other multiple objects.
  • Many-to-one: Many objects associate with one object.

Association is of two types: aggregation and composition.

Composition in Java

Composition in Java is a design technique to implement has-a relationships between classes. In this association, one class contains another class. Moreover, the contained class relies on the containing class and cannot exist independently. In other words, one class includes another class with interdependent functionality. 

For instance, a class ‘Car’ contains classes ‘Engine’ and ‘Battery.’ Thus, ‘Car’ is in a has-a relationship with ‘Engine’ and ‘Battery’, and the latter two cannot exist independently without ‘Car.’

Let’s consider another real-life example. A human body has kidneys, and the organs cannot exist without a human body. Thus, if we think ‘Human’ to be a class with a has-a relationship with the class ‘Kidneys,’ it is composition in Java example since the kidneys cannot exist independently without a human body. 

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

 

Implementing Composition in Java Example

Now consider the following program demonstrating the concept of composition in Java. We will break it down into steps for better understanding.

Step 1: In the first step, we will create a class ‘Car’ and declare and define methods and data members.

class Car

{

// declaring data members and methods

private String color;

private int speed;

public void carFeatures()

{

System.out.println(“Car Color= “+color + ” Maximum Speed= ” + speed);

}

public void setColor(String color)

{

this.color = color;

}

public void setspeed(int speed)

{

this.speed = speed;

}

}

 

Step 2: Next, we will create a class ‘Fiat’ that extends the above class ‘Car.’ The class ‘Fiat’ uses the FiatEngine class object start() method through composition, implying that ‘Fiat’ class ‘has-a’ FiatEngine. Fiat is a car, so it extends from the class ‘Car.’ 

 

class Fiat extends Car

{

//inherits all properties of Car class

public void setStart()

{

FiatEngine e = new FiatEngine();

e.start();

}

}

 

Step 3: In the next step of the Java composition program, we will create a class FiatEngine through which we use the class object in the above class ‘Fiat.’

 

class FiatEngine

{

public void start()

{

System.out.println(“Engine has started.”);

}

public void stop()

{

System.out.println(“Engine has stopped.”);

}

}

 

Step 4: In the final step of the program, we will create a class CompositionExample, make an object of the ‘Fiat’ class, and initialize it.

 

class CompositionExample

{

public static void main(String[] args)

{

Fiat f = new Fiat();

f.setColor(“Black”);

f.setspeed(175);

f.carFeatures();

h.setStart();

}

}

 

Output:

Car Color= Black Maximum Speed= 175

Engine has started.

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

Aggregation and Composition in Java

Aggregation and composition in Java are the two kinds of has-a relationships, with both being different in terms of dependency between classes. In aggregation, the container and reference classes have an independent existence, while a composition reference class ceases to exist without a container class. Thus, a reference class is dependent on its container class in composition.

Here’s a real-life example to understand the difference between aggregation and composition in Java. A car has various parts like an engine, brakes, battery, headlights, music player, etc. While the car can function without a music player, it cannot run without essential parts like an engine or battery. Hence, we can say that the car and the music player have an aggregation relationship while the engine and car have a composition relationship. 

What are the benefits of using composition in Java?

Now that you have a fundamental understanding of the composition concept in Java, here’s an overview of the benefits of this technique:

  • Composition in Java facilitates code reusability.
  • Composition in Java lets us control the visibility of other objects to client classes and reuse what we need.
  • Although Java does not support multiple inheritances, we can work around it using composition.
  • Composition in Java is flexible and lets us change the member objects at runtime to alter the program’s behavior.
  • Java composition offers better class testability, a feature particularly useful in test-driven development.
  • A composition-based design has fewer classes.

Popular Courses & Articles on Software Engineering

Conclusion

Composition in Java is an excellent technique if the relationship between classes is has-a and you are looking to reuse code. Summing up, here are some key points you need to remember about composition in Java:

  • Composition in Java represents a has-a relationship.
  • In composition, one class contains another class, and the contained class relies on the containing class and cannot exist independently. 
  • Both entities in a composition association are dependent on each other.
  • We can achieve composition in Java through an instance variable that refers to other objects.

Enhance your career with upGrad’s Executive PG Program in Software Development

Ads of upGrad blog

Software development is one of the most lucrative career options for young professionals. If you are already in the industry or looking to make a start, you must enroll in upGrad’s Executive PG Program in Software Development. The program teaches you in-demand skills and the ten highest paying coding languages and tools. You can choose from four specializations, including Blockchain Development, Full Stack Development, DevOps, and Cloud Backend Development. 

Along with learning top-paying programming languages, you can work on 30+ Case Studies and Projects. World-class faculty members take live lectures and online sessions for the course. Student support is available on a round-the-clock basis. 

Apply Now to get admission to the course at the earliest!

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

1What is composition and inheritance in Java?

Composition and inheritance in Java are two programming techniques to establish relationships between objects and classes. The composition represents a has-a relationship with one class containing another class. On the other hand, inheritance exhibits an is-a relationship with one class acquiring the properties and behavior of another class.

2What is the purpose of composition in Java?

Composition in Java allows code reusability and provides better testability of a class. Although Java does not support multiple inheritances, the composition provides a way to do so.

3 Is composition an OOP?

Composition is a fundamental concept in object-oriented programming. It describes a has-a relationship where one class references one or more objects of other classes through instance variables.

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6058
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas & Topics
12681
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions & Answers [For Freshers & Experienced]
5669
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions & Answers in US [2024]
5394
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas & Topics For Beginners [US 2023]
10946
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5458
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5558
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5042
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5532
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

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