top of page

Aggregation in java

  • Writer: Keshari Abeysinghe
    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:Mathematics

The 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!

Recent Posts

See All
Inheritance

Inheritance is a mechanism in which one class acquires the property of another class.For example, a child inherits the traits of his/her...

 
 
 
Polymorphism

Polymorphism in Java occurs when there are one or more classes or objects related to each other by inheritance. In other words, it is the...

 
 
 
Abstraction in Java

Abstraction in any programming language works in many ways. It can be seen from creating subroutines to defining interfaces for making...

 
 
 

Comments


Subscribe Form

Thanks for submitting!

©2020 by Quick Code. Proudly created with Wix.com

bottom of page