Aggregation in java

The most important advantage of Object oriented programming is code reusability. Aggregation means making a relationship or association between 2 classes.

There is one directional association between the classes that represent Has-A relationship. As an example suppose, there are 2 classes named as Car and Engine. Class Car has a reference of Class Engine, that means Class Car can acquire all the properties of Class Engine.

It is one directional because, suppose in a garage engine can be removed from the car body and put in some other car as well. So, its existence is not dependent on the existence the car with which it is associated.

In other words, We can say Class Car HAS-A engine.

Aggregation2

Aggregation is the concept where a new object is created by combining with a existing object. It improves the reusability.

Look at the below example, where class Car has a reference of Engine class and proving aggregation.

Output :
Model no is 1234
Engine stated

Why we need Aggregation?

It is used to improve code reusability. We can understand this with an example given below. All other vehicle like bus,truck,bike will also have an engine where the basic functionality of engine will be same like modelno, start and stop. So, the reference of Engine can be used for them.

Bus Has-A Engine

Truck Has-A Engine

Bike Has-A Engine

When to use Aggregation and Inheritance?

When you just want to use the properties and objects of another class without modifying them,then Aggregation can be used. If you want to use and modify the properties and objects of another class, then inheritance can be used.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Print Friendly, PDF & Email
Inheritance in Java
Method Overloading in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *