What is Aggregation?

An association in Java is a relationship between two classes. Aggregation is a special form of association that implies a has-a relationship between a child and a parent class. One of these classes contains a reference to another class, which is established by the objects of these classes. In aggregation, the child class can survive without the parent class, which means that both entities can exist without each other.

A quick example would be a zoo and animals. For a zoo to exist, it must have animals, but an animal can exist without a zoo. The relationship in aggregation is a one-way relationship, which means the child class cannot be composed of the parent.

//example to explain Aggregation
class Animal{
String name;
String breed;
public Animal (String animalName,String animalBreed){
this.name = animalName;
this.breed= animalBreed;
}
}
class Zoo{
String zooName;
Animal animal;
public void display (String zooName,Animal animal){
System.out.println("Zoo" + zooName);
System.out.println("Animal :"+""+animal.name+"" +animal.breed);
}
public static void main (String args[]){
Zoo zoo = new Zoo();
Animal animal = new Animal( "Dog","German Shepherd");
zoo.display("Oba Zoo" ,animal);
}
}

Why use aggregation?

Aggregation allows the code to be reused and enforces the DRY principleDon’t repeat yourself in writing code.

Aggregation vs. composition

  • In composition, classes are interdependent, meaning one cannot exist without the other.

    • This is not the case in aggregation.
  • Think of composition as the relationship between the human body and the heart – the heart cannot exist independent of the body.

  • Aggregation is a weak association, while composition is a strong association.

Copyright ©2024 Educative, Inc. All rights reserved