Let’s dive into the three object-oriented programming concepts..
These concepts describe relationships between objects in a class hierarchy.
We’ll break them down one by one below.
Association
Association represents a “uses-a” or “has-a” relationship between two separate classes where one class uses the other. It defines a relationship between objects where one object can access another.
publicclassDriver{publicstringName{get;set;}}publicclassCar{publicstringModel{get;set;}publicDriverDriver{get;set;}// Association with Driver class}publicclassProgram{publicstaticvoidMain(){Driverdriver=newDriver{Name="John"};Carcar=newCar{Model="Toyota",Driver=driver};Console.WriteLine($"{car.Driver.Name} drives a {car.Model}");}}
Aggregation
Aggregation is a specialized form of Association with a “whole-part” relationship, but the lifetimes of the parts are independent of the whole. In other words, the part can exist without the whole.
publicclassDepartment{publicstringName{get;set;}}publicclassCompany{publicstringName{get;set;}publicList<Department>Departments{get;set;}=newList<Department>();// AggregationpublicvoidAddDepartment(Departmentdepartment){Departments.Add(department);}}publicclassProgram{publicstaticvoidMain(){Departmentd1=newDepartment{Name="HR"};Departmentd2=newDepartment{Name="Finance"};Companycompany=newCompany{Name="TechCorp"};company.AddDepartment(d1);company.AddDepartment(d2);Console.WriteLine($"{company.Name} has the following departments:");foreach(vardeptincompany.Departments){Console.WriteLine(dept.Name);}}}
Composition
Composition is a stronger form of Aggregation with a “part-whole” relationship where the part can’t exist without the whole. If the whole is destroyed, the parts are also destroyed.
Association represents a general relationship where one class uses another. There is no ownership implied. In the example: a Carhas a Driver.
Aggregation defines a specialized form of Association with a “whole-part” relationship where the part can exist independently of the whole. In the example, a Companyhas Departments, but Departmentscan exist without the Company.
Composition describes a strong form of Aggregation where the part cannot exist independently of the whole. If the whole is destroyed, the parts are also destroyed. In the example, a Carhas an Engineand that Enginecannot exist independently of the Car.