OOPS Concepts: Association, Aggregation and Composition
With Object Oriented Programming, we aim for better and easy representation of real world objects. Above oops concepts define relationship between two objects. These relationship define basic functionality which constitutes to OOPS.
Association
It defines that one object has reference of the other. In other words, we can say relationship between two classes defined by their objects. Associativity could be of type one to one, one to many, many to one or many to many.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Employee{ String empName; Address empAdress; int empAge; Employee(String empName, Address empAddress, int empAge){ this.empName = empName; this.empAddress = empAddress; this.empAge = empAge; } } class Address{ String city; String landmark; String societyName; Address(String city, String landmark, String societyName){ this.city = city; this.landmark = landmark; this.societyName = societyName; } |
Above example, we define address of an Employee using Address class object. It defines Aggregation between Employee and Address. In other words, Employee HAS-A Address. This kind of relationship is called HAS A relationship.
Composition
Composition is a special type of Aggregation. Unlike Aggregation, It is more of a restrictive relationship between two classes. If composition of an Object A contains another Object B then if A does not exist, B can not have it’s existence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Company{ String companyName; String CEOName; int numberOfEmp; ArrayList<Employee> empList; Company(String companyName, String CEOName, int numOfEmp, ArrayList<Employee>){ this.companyName = companyName; this.CEOName = CEOName; this.numOfEmp = numOfEmp; this.empList = empList; } } class Employee{ String empName; Address empAdress; int empAge; Employee(String empName, Address empAddress, int empAge){ this.empName = empName; this.empAddress = empAddress; this.empAge = empAge; } } |
In above example, A Company contains number of Employee, Employee can not exist if there is no Company. This relationship is a Composition between Company and Employee.