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.

package com.testingpool;


class Engine{
	int engineModelNo;
	
	Engine(int model){
		this.engineModelNo = model;
	}
	
	void start(){
		System.out.println("Engine stated");
	}
	void stop(){
		System.out.println("Stop started");
	}
	
	int getModelNo(){
		return engineModelNo;
	}
	
}

class Car{
	String CarName;
	Engine e; //Aggregation - reference of class Engine
	
	Car(String car,Engine e){
		this.CarName=car;
		this.e=e;
	}
	
	void Drive(){
		System.out.println("Model no is "+e.getModelNo()); 
		e.start();
	}	
}


public class TestCar {

	public static void main(String[] args) {
		Engine eng = new Engine(1234);
		Car car = new Car("BMW",eng);
		car.Drive();
	}

}
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.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...