In this blog, we can see what is aggregation in java. How it differs from inheritance. And what is the advantage of it.
What is aggregation?
Any class is dependents the other class, that class has the dependent class as the property, And an aggregation represents the HAS-A relationship. So there are no parent class and child class.
Difference between Inheritance and aggregation
Inheritance | Aggregation |
---|---|
Represents IS-A relationship | Represents HAS-A relationship |
The child class inherits the parent class using extends keyword | There are no child and parent class association. So the class can have the dependent class as a property. |
Tightly coupled | Loosely coupled |
Advantage of aggregation
The main advantage of aggregation is code reusability and memory management. And it it loosely coupled. So If need the dependent object we can create objects of dependent class and initialize it at runtime. Otherwise, we can initialize as null.
Example for aggregation
We can take the Employee class. An employee may have two phone numbers or may have only one phone number. When the employee doesn’t have a secondary phone number we can have as null.
package com.samplecoder.aggregation;
public class Employee {
private int id;
private String name;
private String qualification;
private Long primaryPhoneNo;
private Long secondayPhoneNo;
public Employee(int id, String name, String qualification, Long primaryPhoneNo, Long secondayPhoneNo) {
super();
this.id = id;
this.name = name;
this.qualification = qualification;
this.primaryPhoneNo = primaryPhoneNo;
this.secondayPhoneNo = secondayPhoneNo;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", qualification=" + qualification + ", primaryPhoneNo="
+ primaryPhoneNo + ", secondayPhoneNo=" + secondayPhoneNo + "]";
}
}
package com.samplecoder.aggregation;
public class AggregationMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee obj1 = new Employee(1, "Praith", "MCA", Long.valueOf(1234567890), Long.valueOf(1122334455));
System.out.println(obj1);
Employee obj2 = new Employee(2, "Heshika", "MBA", 1122334455L, null);
System.out.println(obj2);
}
}
