Introduction
Association, Aggregation and Composition are terms that represent relationships among objects. They are very basic stuff of Object Oriented Programming.
Association
Association is a relationship among the objects. Association is "*a*" relationship among objects. In Association, the relationship among the objects determine what an object instance can cause another to perform an action on its behalf. We can also say that an association defines the multiplicity among the objects. We can define a one-to-one, one-to-many, many-to-one and many-to-many relationship among objects. Association is a more general term to define a relationship among objects. Association means that an object "uses" another object.
For example Managers and Employees, multiple employees may be associated with a single manager and a single employee may be associated with multiple managers.

Aggregation
Aggregation is a special type of Association. Aggregation is "*the*" relationship among objects. We can say it is a direct association among the objects. In Aggregation, the direction specifies which object contains the other object. There are mutual dependencies among objects.
For example, departments and employees, a department has many employees but a single employee is not associated with multiple departments.
UML Representation of Aggregation (white diamond):

The UML representation of the example above (relation between employee and department):

Here, the lives of both objects are independent of each other. That means that in this Association (Aggregation) the object has their own life cycle. Employees may exist without a department. Here, department can be called an owner object and the employee can be called a child object. The owner and child objects cannot belong to a different parent object.
Composition
Composition is special type of Aggregation. It is a strong type of Aggregation. In this type of Aggregation the child object does not have their own life cycle. The child object's life depends on the parent's life cycle. Only the parent object has an independent life cycle. If we delete the parent object then the child object(s) will also be deleted. We can define the Composition as a "Part of" relationship.
For example, the company and company location, a single company has multiple locations. If we delete the company then all the company locations are automatically deleted. The company location does not have their independent life cycle, it depends on the company object's life (parent object).
UML Representation of Composition (black diamond):

UML representation of the example above (relation between Company and Company Location):

Here, the lives of both objects are not independent. The life of the company location object can be determined by the life of the company object. The company object is responsible for creating and destroying company location objects.
Relationship among Association, Aggregation and Composition

Aggregation and Composition are a special type of Association. Composition is again a special type of Aggregation. We can define Aggregation and Composition as "has a" relationships. Composition is more restrictive or more specific. In Composition, composed objects cannot exist without the other object. This type of restriction does not exist in Aggregations. In Aggregation, the existence of a composed object is optional. In Aggregation, the child object can exist beyond the life cycle of its parent whereas in Composition the child object cannot exist beyond the life cycle of its parent.
Combined example of Aggregation and Composition:

Aggregation VS Composition
Aggregation | Composition |
Aggregation is a special type of Association. | Composition is a special type of Aggregation. |
All objects have their own life cycle. | In Composition, the child object does not have their own life cycle and it depends on the parent's life cycle. |
A parent class is not responsible for creating or destroying the child class. | The parent class is responsible for creating or destroying the child class. |
Aggregation can be described as a "Has-a" relationship. | Composition can be described as a "Has-a" relationship as well as a "Part of" relationship, but here the difference is the length of the relationship among the objects. |
Aggregation is a weak Association. | Composition is a strong Association. |
Aggregation means one object is the owner of another object. | Composition means one object is contained in another object. |
The direction of a relation is a requirement in both Composition and Aggregation. The direction specifies which object contains the other one. | |
Both have a single direction of association. | |
Both have a single owner. |
Conclusion
These
three terms are more important in the object oriented world. They
denote or represent the relations among objects. If you are confused or
unable to decide whether a specific relation best describes an
Association, Aggregation or Composition then it can be decribed as an
AssociationIntroduction:
Apart from programming, a lot of my spare time sat at the computer is spent reading group, blog postings, etc from other developers. One particular posting that caught my eye recently provoked a lot of response and mixed answers to a question posed by a poster. This question was, 'What is the difference between composition and aggregation and how would I express it in my programs'?
Reading the responses to the post, I had a mixed reaction, many of the responses reflected my understanding of the difference, others turned my understanding right around and explained composition as my understanding of aggregation.
This short article will put forward my understanding of composition and aggregation and how I would express it in C# code.
Composition:
As we know, inheritance gives us an 'is-a' relationship. To make the understanding of composition easier, we can say that composition gives us a 'part-of' relationship. Composition is shown on a UML diagram as a filled diamond (see Figure 1).

public class Engine
{
. . .
}
public class Car
{
Engine e = new Engine();
.......
}
As you can see in the example code above, Car manages the lifetime of Engine. Aggregation:If inheritance gives us 'is-a' and composition gives us 'part-of', we could argue that aggregation gives us a 'has-a' relationship. Within aggregation, the lifetime of the part is not managed by the whole. To make this clearer, we need an example. For the past 12+ months I have been involved with the implementation of a CRM system, so I am going to use part of this as an example.
The CRM system has a database of customers and a separate database that holds all addresses within a geographic area. Aggregation would make sense in this situation, as a Customer 'has-a' Address. It wouldn't make sense to say that an Address is 'part-of' the Customer, because it isn't. Consider it this way, if the customer ceases to exist, does the address? I would argue that it does not cease to exist. Aggregation is shown on a UML diagram as an unfilled diamond (see Figure 2).

So
how do we express the concept of aggregation in C#? Well, it's a little
different to composition. Consider the following code:
public class Address{
. . .
}
public class Person
{
private Address address;
public Person(Address address)
{
this.address = address;
}
. . .
}
Person would then be used as follows:
Address address = new Address();
Person person = new Person(address);
Person person = new Person(address);
or
Person person = new Person( new Address() );
As
you can see, Person does not manage the lifetime of Address. If Person
is destroyed, the Address still exists. This scenario does map quite
nicely to the real world.
Conclusion:
As
I said at the beginning of the article, this is my take on composition
and aggregation. Making the decision on whether to use composition or
aggregation should not be a tricky. When object modelling, it should be a
matter of saying is this 'part-of' or does it 'have-a'?Aggregation Vs Composition: A Simple Practical Approach
The question is, "What is the difference between composition and aggregation?" In this article I'll provide my understanding of composition and aggregation.
The following image is fictional and it may be one of the possible scenarios with warrior's fight.

AggregationAggregation means “The act of gathering something together”.
As inheritance gives us an "is-a" and composition gives us a "part-of" whereas aggregation gives us a "has-a" relationship.
For example, a mobile “has an” operating system. Aggregation doesn't manage the lifetime of other objects. For an example, mobile uses (has-an) operating system that may be of a different service provider. like Android, iOS and Windows. Here Aggregation theory says that a mobile has an operating system of a specific service provider.
Aggregation diagram is shown as a UML diagram with unfilled diamond notation as depicted below:

The preceding diagram states that a Mobile class may utilize an operating system from a different service provider. A mobile is not directly dependent on an operating system class. Both are independent entities. For example a Samsung is a mobile provider whereas an Android is a Google Product.
A code snippet shown below that is an OperatingSys object is injecting into the Mobile class at the constructor level. The creation of the OperatingSys class is entirely independent from Mobile Creation. Kindly have a look at the code segment as shown below:
- public class Mobile
- {
- public OperatingSys objOS;
- public Mobile(OperatingSys objOperatingSys)
- {
- this.objOS = objOperatingSys;
- }
- public string MobileName { get; set; }
- public string OperatingSystem { get; set; }
- public string GetMobileDetails()
- {
- return objOS.OSName() + " Used by " + MobileName;
- }
- }
- public class OperatingSys
- {
- public string OS { get; set; }
- public string OSName()
- {
- return "This is Android OS being";
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- OperatingSys objOperatingSys = new OperatingSys();
- Mobile objMobile = new Mobile(objOperatingSys);
- objMobile.MobileName = "Samsung";
- Console.WriteLine(objMobile.GetMobileDetails());
- Console.ReadLine();
- }
- }
Composition gives us a "part-of" relationship or a mixture of ingredients. Composition is a higher degree of association than aggregation. Composition derives the management of the objects and its lifecycle. In case of composition the lifetime of the owned object is the responsibility of the owner object. Composition is shown on a UML diagram as a filled diamond as depicted below in the screen.

As you can see in the example code snippet below, Mobile manages the lifetime of DisplayScreen, since the DisplayType object depends on the Mobile object. If Mobile is garbage collected, the DisplayType object is also garbage collected.
- public class Mobile
- {
- public string MobileName { get; set; }
- public string DisplayType { get; set; }
- public Mobile()
- {
- }
- public string GetMobileDetails()
- {
- return this.DisplayType + " Used by " + this.MobileName;
- }
- }
- public class DisplayScreen
- {
- public static string ScreenType()
- {
- return "This LED screen display";
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- // OperatingSys objOperatingSys = new OperatingSys();
- Mobile objMobile = new Mobile();
- objMobile.MobileName = "Samsung Galaxy Mobile";
- objMobile.DisplayType = DisplayScreen.ScreenType();
- Console.WriteLine(objMobile.GetMobileDetails());
- Console.ReadLine();
- }
- }

Note: It might be one of the questions in an interview.
Extending your code
Extensibility of a class doesn't always depend on inheritance. Using composition and aggregation relationships between classes, we can create more cohesive and loosely coupled modules. Did I say no inheritance?

Let's first understand composition and aggregation in the real world. Let's say you are a student pursuing studies in a college in the Computer Science department. If you are wearing the Object Oriented Analysis and Design (OOAD) shoes you could easily understand the entities from the scenario. You guessed it! Student, College and Department.
A college has many departments and many students. The departments of the college can't exist without the college itself . This means “Departments” are owned by the college. Students can exist without the college, the ownership of students are not in the college alone. Students can look for a new college if the college doesn't exist. Can you identify a composition and aggregation relationship?
Composition is the idea of an object could be made up of, or composed of, other objects. The composed objects are intrinsic to the main object. Aggregation states that an object can bring together separate objects that has their own life time. The relation between body and heart is composition whereas car and wheel is aggregation.

Let's look at a more practical example in Java. An employee has an address and insurance. The insurance is optional for the employee but the employee should always have an address.

The lifetime of the address instance is intrinsic to the employee instance, but an insurance instance can exist on its own. If you see the code below in the Test class, once the employee instance is created, the address instance is also created within the employee class. The insurance instance is set explicitly and it is optional for an employee.
- public class Test {
- public static void main(String[] args) {
- Employee kannan = new Employee("kannan sudhakaran", "Andheri", "mumbai", "Maharashtra", "5055");
- System.out.println(kannan);
- //add via aggregation
- InsuranceInfo insuranceInfo = new InsuranceInfo();
- insuranceInfo.setPolicyId("1001");
- insuranceInfo.setPolicyName("Life Insurance policy");
- kannan.setInsurance(insuranceInfo);
- System.out.println(kannan);
- }
- }

A quick sketch of the class diagram should look like this.

The following is the implementation in Java.
- // Employee.Java
- package com.techlabs.composition.aggregation;
- public class Employee {
- private String name;
- private AddressInfo address;
- private InsuranceInfo insurance; // may or may not
- public Employee(String name, String street, String city, String state, String postalCode) {
- this.name = name;
- this.address = new AddressInfo();
- address.setCity(city);
- address.setState(state);
- address.setPostalCode(postalCode);
- address.setStreet(street);
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public AddressInfo getAddress() {
- return address;
- }
- public void setAddress(AddressInfo address) {
- this.address = address;
- }
- public InsuranceInfo getInsurance() {
- return insurance;
- }
- public void setInsurance(InsuranceInfo insurance) {
- this.insurance = insurance;
- }
- @Override
- public String toString() {
- StringBuilder retValue = new StringBuilder();
- retValue.append(name).append(" ")
- .append(address.getStreet()).append(" ")
- .append(address.getCity()).append(" ")
- .append(address.getState()).append(" ");
- if (insurance != null) retValue.append(insurance.getPolicyId()).append(" ")
- .append(insurance.getPolicyName());
- return retValue.toString();
- }
- }
- // AddressInfo.Java
- package com.techlabs.composition.aggregation;
- public class AddressInfo {
- private String street;
- private String city;
- private String state;
- private String postalCode;
- public String getStreet() {
- return street;
- }
- public void setStreet(String street) {
- this.street = street;
- }
- public String getCity() {
- return city;
- }
- public void setCity(String city) {
- this.city = city;
- }
- public String getState() {
- return state;
- }
- public void setState(String state) {
- this.state = state;
- }
- public String getPostalCode() {
- return postalCode;
- }
- public void setPostalCode(String postalCode) {
- this.postalCode = postalCode;
- }
- }
- //InsuranceInfo.Java
- package com.techlabs.composition.aggregation;
- public class InsuranceInfo {
- private String policyName;
- private String policyId;
- public String getPolicyName() {
- return policyName;
- }
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
- public String getPolicyId() {
- return policyId;
- }
- public void setPolicyId(String policyId) {
- this.policyId = policyId;
- }
- }
Designing an application using Object Oriented Programming is inevitable due to the features it provides, like inheritance, polymorphism, encapsulation and so on. Apart from these concepts, it is very important to understand some logical concepts along with technical concepts so that writing the code is easy, clean and re-usable. This article will explain some of the concepts we use in most of the classes that we write, even if we don't know we have implemented the concept.
Relationships, as the name suggests, defines the dependency/association/same kind in the components of a system in real life. The same for Object Oriented Programming that involve many of classes and most of these classes are somehow dependent/associated or similar to one or the other class. So broadly speaking, we have the concept of relationships with the following 3 categories:
- Dependency: also called a using relationship, which means, one class is dependent on another class.
- Generalization: also called an "is-a-kind-of" relationship.
- Association: also called a "has-a" relationship that says one class is somehow associated with another class.
To explain these concepts, I will refer to my understanding of my study, along with examples from the book named "The Unified Modeling Language User Guide" by Grady Booch, James Ramabaugh and Ivar Jacobson.
So let's start with it.
Dependency
Dependency is defined as a relation between two classes, where one class depends on another class but another class may or not may depend on the first class.So any change in one of the classes may affect the functionality of the other class, that depends on the first one.
For examle, we have a Customer class and an Order class. When we need to save a new order, we need to save it corresponding to a customer. In order to do so, our Order class will need a reference to the Customer class and save its data. So in this case, our Order class is dependent on the Customer class. In the future, if any change are made to the Customer class, it may result in changes to the Order class. See the code below:

In the code above, we have a CustomerId as a GUID. The Order class uses this customer instance. If we change the data type of the CustomerId from GUID to integer, it will affect the Order class. This kind of relation is known as a Dependency and is represented by the following symbol in a UML representation:

Generalization
All of us know about the concept of inheritance. It is nothing but a kind of generalization. We define it simply with a base class having some properties, functions and so on. A new class will be derived from this base class and the child class will have access to all the functionality of the base or parent class (of course depending on the access modifiers defined on the base class members).
It is also referred to as a "is-a-kind-of" or "is-a" relationship; that means that the child class is-a-kind-of a base class. This provides the ability to define common properties for derived classes in a common place and use of them depends on the derived class requirements.
For example: we have a base class named Vehicle and a derived class named Car, from the base class. So Car will have access to all the functions, properties and so on of the base class Vehicle (depending on the access modifiers defined for base class members). See the code below:

Here we have common properties like color and price in the base class that can be set depending on the derived class's requirements. Apart from these, it will add its specific property named Discount. But this class will not have access to the base class property VehicleType, since it is a private type. The same will be applicable for any other class that derives from the Vehicle class and any other member defined in the base class. Generalization is represented by the following symbol in UML:

Association
Association is defined as a structural relationship, that conceptually means that the two components are linked to each other. This kind of relation is also referred to as a using relationship, where one class instance uses the other class instance or vice-versa, or both may be using each other. But the main point is, the lifetime of the instances of the two classes are independent of each other and there is no ownership between two classes.
For example, consider the same example of a Student-Teacher relationship. Conceptually speaking, each student can be associated with multiple teachers and each teacher can be associated with multiple students. Now to explain this relationship in terms of Object Oriented Programming, see the code below:

Here, we have a single student instance "_student". This student can have multiple teacher class instances associated with it, in other words "_teacher1" and "_teacher2".
- First, both of these instances are being created outside the student class. So their lifetime is independent of the lifetime of the instance of the student. So even if "_student" is disposed of explicitly, we can still have the teacher class instances as alive.
- Secondly, any other student instance, say _student2, can also have the same instances of teacher, in other words "_teacher1" and "_teacher2" associated with it. So we can also say that no instance of student is a parent of any instance of teacher. So there is no ownership of instances in the association.
This association is represented by the following symbol in UML:

So that described association. Now for the specialized cases of association, aggregation and composition.
- Aggregation: Aggregation is the same as association but with an additional point that there is an ownership of the instances, unlike association where there was no ownership of the instances. To understand it better, let's add another class named Department to our example explained above.

Here, we have a department instance "_department1" and multiple instances of teacher, in other words "_teacher1" and "_teacher2".
- First, the lifetime of "_teacher1" and "_teacher2" instances are independent of the lifetime of a "_department1" instance, since they are instantiated outside the department class. So even if a "_department1" instance is disposed if, "_teacher1" and "_teacher2" instances may continue to exist.
- Secondly, "_department1" can have multiple instances of teacher associated with it, but the reverse is not true, in other words "_teacher1" and "_teacher2" can belong to "_department1" only. They cannot belong to any other instance like department2. So "_department1" becomes the owner of the "_teacher1" and "_teacher2" instances. So here the ownership exists.
Aggregation is also referred to as a Weak Association and is represented by the following symbol in UML representation:

- Composition: This is the same as that of aggregation, but with the additional point that the lifetime of the child instance is dependent on the owner or the parent class instance. To the same code above, let's add another class named University.

- First, each department instance, in other words "_department1" and "_department2", can belong only to a single university instance at a time, _university1. But a university instance can have multiple department instances attached to it. So this makes the "_university1" instance the owner of the "_department1" and "_department2" instances. So this is the inherited feature of the aggregation in composition.
- Secondly, here the lifetime of department instances are dependent on the instances of university, since they are being created inside the university class. So when the "_university1" instance is disposed of the "_department1" and "_department2" instances are also killed. This is the composition concept.

So if we closely observe the concepts of Association, Aggregation and Composition, we can say that composition is a subset of association and aggregation and aggregation is a subset of association. In other wors, Association is a super-set of aggregation and composition can be represented as:

So this was all about these concepts and we can say that we were using these concepts in our programming but were not aware of their actual existence.
This article explains Aggregation in Java along with well explained illustrations for a better understanding.
Consider the situation that a student has his name, roll number and id along with an address that consists of city, pin code, state, and so on. In this case the student has an entity reference address; that means the student has an address.
Aggregation represents a "has-a" relationship.
If a class has an entity reference then it is known as aggregation.
Aggregation is useful for code reusability.
class Student
{
int id;
int rollno;
String name;
Address address; //Address is a class
}
The following is a simple example to understand the concept of aggregation.

In this example, we created the reference to the calculation class in the circle class.
class Calculation
{
int multiply(int n)
{
return 2*n;
}
}
class Circle
{
Calculation cal; //aggregation
double pi=3.14;
double circumference(int radius) {
cal=new Calculation();
int nmultiply=cal.multiply(radius); ///code reusability
return pi*nmultiply;
}
public static void main(String args[]) {
Circle c=new Circle();
double result=c.circumference(7);
System.out.println(result);
}
}
Output: 43.96
When aggregation is used
We use aggregation when we need to reuse code and there is no "is-a" relationship.
Inheritance should be used whenever there exists an "is-a" relationship, otherwise aggregation is the best.
Another example for understanding aggregation.
There are two Java files, both public classes.
Address.java
public class Address
{
String city,state,country;
int pin;
public Address(String city,String state,String country,int pin)
{
this.city=city;
this.country=country;
this.state=state;
this.pin=pin;
}
}
Student.java
public class Student
{
int id;
String name;
Address address;
public Student(String name,int id,Address address)
{
this.address=address;
this.name=name;
this.id=id;
}
void display() {
System.out.println(id+""+name);
System.out.println(address.city+""+address.state+""+address.country+""+address.pin);
}
public static void main(String args[]) {
Address address1=new Address("Jhansi","UP","India",284003);
Address address2=new Address("Lucknow","UP","India",230056);
Student student1=new Student("Rahul",1000,address1);
Student student2=new Student("Shubham",2000,address2);
student1.display();
student2.display();
}
}
Output: 1000Rahul
JhansiUPIndia284003
2000Shubham
LucknowUPIndia23005
My earlier article was about Association in OOP. Then I got comments and feedback requesting that I write and explain more about other features. So, here we are going to talk about Aggregation and Composition in OOAD.
Look at the picture below and see what we can understand from it.
I can see:
- A student
- A Library
- Books
Can we say that all of these are objects?
The answer is yes. Now try to establish a relationship between them. in other words Association.
- A student can have a one-to-one relationship with the library.
- A library can have one-to-many relationships with books.
- Can a student object exist without a library?
Answer: Yes, a student may or may not be associated with a library. This is Aggregation.
- Can a library object exist without books?
Answer: No, a library is of no use without books. In short, if there are no books there is no library. This is Composition.
- Both Aggregation and Composition are subsets of Association.
- Aggregation is a type of Association with has-a relationship.
For example A library has a student.
- Composition has a direct dependency on the other objects. That means the object's existence depends on the other primary object.
For example, a library cannot exist without books. So if there are no books there is no library.
No comments:
Post a Comment