In Object-Oriented Programming (OOP), aggregation and composition are two types of association that represent relationships between objects. They are used to build complex systems by combining simpler objects.
Aggregation
Aggregation is a type of association that represents a "has-a" relationship where the contained objects can exist independently of the container object. It is used to model a relationship where the lifecycle of the contained objects is not tightly bound to the lifecycle of the container object.
Composition
Composition is a type of association that represents a "has-a" relationship where the contained objects cannot exist independently of the container object. The container object is responsible for the creation and destruction of the contained objects, implying a strong lifecycle dependency between the container and its contained objects.
C# Examples
Aggregation Example
using System;
using System.Collections.Generic;
class Student
{
public string Name { get; set; }
public Student(string name)
{
Name = name;
}
}
class University
{
public List<Student> Students { get; private set; }
public University()
{
Students = new List<Student>();
}
public void AddStudent(Student student)
{
Students.Add(student);
}
}
class Program
{
static void Main(string[] args)
{
Student student1 = new Student("Alice");
Student student2 = new Student("Bob");
University university = new University();
university.AddStudent(student1);
university.AddStudent(student2);
Console.WriteLine("University has the following students:");
foreach (var student in university.Students)
{
Console.WriteLine(student.Name);
}
}
}
Composition Example
using System;
using System.Collections.Generic;
class Room
{
public string Name { get; set; }
public Room(string name)
{
Name = name;
}
}
class House
{
public List<Room> Rooms { get; private set; }
public House()
{
Rooms = new List<Room>
{
new Room("Living Room"),
new Room("Bedroom"),
new Room("Kitchen")
};
}
public void DisplayRooms()
{
Console.WriteLine("House contains the following rooms:");
foreach (var room in Rooms)
{
Console.WriteLine(room.Name);
}
}
}
class Program
{
static void Main(string[] args)
{
House house = new House();
house.DisplayRooms();
}
}
Explanation
Aggregation:
- In the
University
class, theStudents
list contains instances of theStudent
class. - The
Student
instances are created outside theUniversity
class and then added to theUniversity
'sStudents
list. - The
Student
instances can exist independently of theUniversity
.
- In the
Composition:
- In the
House
class, theRooms
list contains instances of theRoom
class. - The
Room
instances are created within theHouse
class, indicating that theHouse
class is responsible for their creation. - If the
House
object is destroyed, theRoom
objects would also be destroyed, showing a strong lifecycle dependency.
- In the