What is aggregation in Java?

Java 8Object Oriented ProgrammingProgramming

When an object A contains a reference to another object B or we can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation.

Aggregation helps in reusing the code. Object B can have utility methods and which can be utilized by multiple objects. Whichever class has object B then it can utilize its methods.


public class Vehicle{}
public class Speed{}

public class Van extends Vehicle {
   private Speed sp;

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.

In the Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action. This concept of containing an object to do action is termed as Aggregation.

Published on 29-Dec-2017 09:43:25