Code difference between Aggregation and Composition

778 views Asked by At

Can anyone give code example to show the difference between Aggregation and Composition. I have already Read This and did not understood how they differ in code.

Please show the difference through code.

1

There are 1 answers

0
sanderarts On

The main difference between a composition and an aggregation is that a composition is a 1-on-1 relation and aggregation a 1-to-many. To be clear: a class has only one professor and therefore it is a composition relation and a class can have multiple students so it is an aggregation.

To translate this to actual code a Class-object (class in the sense of a class in school) could have a list of students and only a single Professor field. This would indicate that the class has a 1-to-many relationship with students but a 1-on-1 relationship with a professor.

For example in code:

public class SchoolClass
{
    Professor mProfessor;
    List<Student> mStudents;
}