Aggregation

When the reference of a class act as a member in another class is known as Aggregation.

Aggregation represents HAS-A relationship. Consider a situation, Employee object contains many information such as id, name etc. It contains one more object named address, which contains its own information such as city, state, country etc.

It represent the concept of inheritance without no IS-A relationship. 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.

Let's see an example for better understanding this concept.


Address.java

 

package java8s;

public class Address {
      String city, state, country;
     
      Address(String city, String state, String country)
      {
            this.city=city;
            this.state=state;
            this.country=country;
      }

}

AgreegationExample.java

package java8s;

class Employee
{
      int id;
      String name;
      Address ad;
      Employee(int id, String name, Address ad)
      {
            this.id=id;
            this.name=name;
            this.ad=ad;
      }
     
      void show()
      {
            System.out.println(id+" "+name);
            System.out.println(ad.city+" "+ad.state+" "+ad.country);
      }
}
public class AgreegationExample {

      public static void main(String[] args) {
           
            Address ob1=new Address("BBSr","Odisha","india");
            Employee e=new Employee(101,"Trilochan",ob1);
            e.show();

      }

}

 

Output
aggregation
Note:

When we need to use property and behaviour of a class without modifying it inside our class then we use Aggregation as better, Whereas when we need to use and modify property and behaviour of a class inside our class, then we use Inheritance as better.

 

 

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment