superman
superman

Reputation: 377

association, aggregation and composition example

association, aggregation and composition

I want to get the illustration for above three with simple classes. I read a lot from internet. The conclusion is as-

In aggregation people say-

"Class A contains collection of another Class (say B) and if A is destroyed it will not affect its child that is collection will not be destroyed." How is it possible if one object is destroyed but its property can still exist or what they mean by this.(Am I misinterpreting something)

Class A
{
List<B> lst;
}

Class B
{

}

Upvotes: 0

Views: 4201

Answers (1)

Devendra D. Chavan
Devendra D. Chavan

Reputation: 9031

Consider the following classes,

class Student
{
    public string Id { get; set; }
    public string Name { get; set; }
}

class Department
{
    public IList<Student> Students { get; set; }

    public void AddStudent(Student student)
    {
        //...
    }

    public void RemoveStudent(Student student)
    {
        //...
    }
}

If you want to add a student to the department, then you call AddStudent() and pass the reference of the Student class instance (note that a reference is passed). So when the department instance is destroyed (set to null for example), then the Students property of that Department instance is no longer available, but the Student instances that have been used to populate this list remain are not destroyed. Hence, the property, in this case a Student instance can still exist.

More information

Upvotes: 2

Related Questions