The relationship between two classes known as "aggregation" in Java is best described as a "has-a" and "whole/part" relationship. This association relationship is a more specialised variation. The aggregate class is said to own the other class because it contains a reference to it. Every class that is cited is taken to be a component of the aggregate class.
for example student object(schoolStudent) contains many informations such as id, name etc. It contains one more object named subjects , which contains its own informations such as name of book and price as given below.
// Java example of Aggregation
class Subjects { String BookName; int bookPrice; public Subjects(String bookName, int bookPrice) { BookName = bookName; this.bookPrice = bookPrice; } } public class SchoolStudent { String name; int id; Subjects subjects ; SchoolStudent(String name, int id, Subjects subjects){ this.name = name; this.id = id; this.subjects = subjects; } public static void main(String[] args) { Subjects subjects = new Subjects("Math",321); SchoolStudent schoolStudent=new SchoolStudent("Alok", 12,subjects); System.out.println("Student Name :"+schoolStudent.name); System.out.println("Student ID :"+schoolStudent.id); System.out.println("Book Name :"+schoolStudent.subjects.BookName); System.out.println("Book Price :"+schoolStudent.subjects.bookPrice); } }
Output:
Student Name :Alok
Student ID :12
Book Name :Math
Book Price :321
// Java example of Aggregation
class Address { String city,state,country; public Address(String city, String state, String country) { this.city = city; this.state = state; this.country = country; } } public class SchoolStudent { int RollNo; String StudentName; Address Studentaddress; public SchoolStudent(int RollNo, String StudentName,Address Studentaddress) { this.RollNo = RollNo; this.StudentName = StudentName; this.Studentaddress=Studentaddress; } void display(){ System.out.println("RollNo :"+RollNo+" Name : "+StudentName); System.out.println(Studentaddress.city+" "+Studentaddress.state+" "+Studentaddress.country); } public static void main(String[] args) { Address Studentaddress=new Address("Patna","Bihar","India"); Address Studentaddress2=new Address("Pune","Maharashtra","India"); SchoolStudent schoolStudent=new SchoolStudent(401395,"Alok",Studentaddress); SchoolStudent schoolStudent2=new SchoolStudent(401398,"Ankita",Studentaddress2); schoolStudent.display(); schoolStudent2.display(); } }
Output:
Student Name :Alok
Patna Bihar India
RollID :401398 Name : Ankita
Pune Maharashtra India
Post your comment