Java Tutorial

What is Java


Control Statements


Java Object Class


Java Inheritance


Java Polymorphism


Java Abstraction


Java Encapsulation


Java Array

Java OOPs Misc


Java Array

Java OOPs Misc


Aggregation in Java

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.

Flash Soon


In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Why use Aggregation?

  1. For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

Flash Soon


Output:

When use Aggregation?

  1. Code reuse is also best achieved by aggregation when there is no is-a relationship.
  2. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation

In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship is Employee HAS-A address.

Address.java

Flash Soon


Emp.java

Flash Soon


Output:

Advertisement

Copyright ©2017 Design& development