Aggregation in Java

Aggregation is a term which is used to refer one way relationship between two objects. It is a form of HAS-A relationship between two classes. Aggregation in Java allows us to provide a reference for one class within another class.

We should not confuse aggregation with Inheritance. Inheritance should be used for IS-A relationship between the objects involved, otherwise aggregation is the best option for HAS-A relationship.

Real life examples of aggregation(has-a relationship)

  1. A Bus has a steering wheel but vice versa is not possible and thus it is unidirectional in nature.

  2. A Manager object contains many informations such as name, emailId etc. It contains one more object named address, which contains its own informations such as city, state etc. Manager object contains a reference of Address object, so relationship is Manager HAS-A address.
class Address {
   String city;
   String state;
   ...
}

class Manager {
   String name;
   String emialId;
   Address address; 
}

Java program for aggregation relationship

class Address {
  String city;
  String state;
	String zipcode;

  Address(String city, String state, String zipcode) {
    this.city = city;
    this.state = state;
    this.zipcode = zipcode;
  }

  @Override
  public String toString() {
    return String.format("%s, %s, %s", city, state, zipcode);
  }
}

// Manager has an Address reference
class Manager {
  Manager(String name, String emialId, Address address) {
    this.name = name;
    this.emialId = emialId;
    this.address = address;
  }

  String name;
  String emialId;
  // Has-A relationship
  Address address;
}

public class AggregationJava {
  public static void main(String[] args) {
    Address address = new Address("Miami", "Florida", "12345" );
    Manager manager = new Manager("John", "abc@gmail,com", address);

    // Printing Manager Address
    System.out.println(manager.address.toString());
  }
}
Output
Miami, Florida, 12345

The above program, shows the Aggregation between Manager and Address classes. You can see that Manager class contains a property of type Address to obtain manager's address. Its a typical example of Aggregation(Has-A) relationship in Java.

Advantages of Aggregation

The main advantage of using aggregation is to maintain code re-usability. If an entity has a relation with some other entity than it can reuse code just by referring that.