1.

Aggregation in Java

Answer»

Aggregation is a type of weak association that specifies a HAS-A relationship. Both the objects of a class in an aggregation can EXIST individually. Also, aggregation is a one-way relationship. For example - A class in a school has STUDENTS but the opposite is not true.

A program that demonstrates aggregation in Java is given as FOLLOWS:

class School {    private String name;    School(String name)    {        this.name = name;    }    public String retClassName()    {        return this.name;    } }   class Student {    private int rno;    private String name;    Student(int rno, String name)      {        this.rno = rno;        this.name = name;    }    public String retStudentName()    {        return this.name;    } } public class AssociationDemo {    public static void main (String[] args)      {        School c = new School("XII B");        Student s1 = new Student(1, "John");        Student s2 = new Student(2, "Susan");        Student s3 = new Student(3, "Mary");        Student s4 = new Student(4, "ADAM");        Student s5 = new Student(5, "Lucy");        System.out.println("The students in school class " + c.retClassName() + " are:") ;        System.out.println(s1.retStudentName());        System.out.println(s2.retStudentName());        System.out.println(s3.retStudentName());        System.out.println(s4.retStudentName());        System.out.println(s5.retStudentName());    } }

The output of the above program is as follows:

The students in school class XII B are: John Susan Mary Adam Lucy

In the above program, there is a HAS-A relationship between School class and student as a class in a school has multiple students.



Discussion

No Comment Found