Tuesday, August 2, 2016

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 relationships 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.

class Company{
 String companyName;
 String CEOName;
 int numberOfEmp;
 Company(String companyName, String CEOName, int numOfEmp){
 this.companyName = companyName;
 this.CEOName = CEOName;
 this.numOfEmp = numOfEmp;
 }
}

class Employee{
 String empName;
 String empAdress;
 int empAge;
 Employee(String empName, String empAddress, int empAge){
 this.empName = empName;
 this.empAddress = empAddress;
 this.empAge = empAge;
 }
}

Here, we can say Employee A works in Company B. This is one to one relationship. An Employee and a Company has association.

 Aggregation
Aggregation is a special type of Association. It also determines relationship between two objects but it is directional relationship i.e. it is one-way association defining which object comprises another object. It is also referred as HAS-A relationship.

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.

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 cannot have its existence.
class Company{
String companyName;
String CEOName;
int numberOfEmp;
ArrayList empList;
Company(String companyName, String CEOName, int numOfEmp, ArrayList){
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 cannot exist if there is no Company. This relationship is a Composition between Company and Employee.

No comments:

Post a Comment