Aggregation in java
- Keshari Abeysinghe

- Mar 25, 2020
- 1 min read
Updated: Nov 30, 2020
In Java, aggregation represents HAS-A relationship, which means when a class contains reference of another class known to have aggregation.The main advantage of using aggregation is to maintain code re-usability. Code reuse is also best achieved by aggregation when there is 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.
Following example shows the how use aggregation in java.
class Student
{
String studentName;
int age;
String subject;
// Student class constructor
Student(String name, int age, String subject)
{
this.studentName = name;
this.age = age;
this.subject = subject;
}
}
class School{
String name;
int price;
// student details
Student student;
School(String n, int p, Student student )
{
this.name = n;
this.price = p;
this.student = student;
}
}
public static void main(String[] args) {
Student student= new Student("John", 42, "Mathematics");
School s = new School("Montaro", 800, student);
System.out.println("School Name: "+s.name);
System.out.println(" Price: "+s.price);
System.out.println("------------Student Details----------");
System.out.println("Student Name: "+s.student.studentName);
System.out.println("Student Age: "+s.student.age);
System.out.println("Student Subject: "+s.student.subject);
}
}
Expected output:
School Name:Montaro
Price:800
------------Student Details----------
Student Name:John
Student Age:42
Student Subject:MathematicsThe aggregation mostly used when you want to use some property or behavior of any class without the requirement of modifying it or adding more functionality to it, in such case Aggregation is a better option because in case of Aggregation we are just using any external class inside our class as a variable.
Happy Coding!
Comments