Inheritance, Association, Aggregation, and Composition
1. Inheritance [IS a relationship]
2. Association [Using Relationship]
3. Aggregation [ Has a Relationship]
4. Composition - [Part of relationship]
1.
Inheritance [ IS a relationship]
Example
Consider there are two Classes.
1.Employee
2.Manager
Here Employee is the Parent class; Manager is the child
class.Manager is one of the types of Employee. Class Manager is a relation with
Class Employee.
I.e. Manager is (a or an) Employee
2. Association [Using relationship]
Example
1. Manager
2. SwipeCard
Here Manager and
SwipeCard are two different classes.
Manager uses a swipe
card to enter XYZ premises.
I.e. Manager Using
swipe card to enter XYZ premises.
The above diagram
shows how the SwipeCard class uses the Manager class and
the Manager class uses the SwipeCard class. You can also see how
we can create objects of the Manager class
and SwipeCard class independently and they can have their own object
life time.
This relationship
is called the “Association” relationship.
3. Aggregation [ Has a
Relationship]
Aggregation gives
us a 'has-a' relationship. Within aggregation, the lifetime of the part is not
managed by the whole.
The above UML describes Aggregation relation which mentions that Employee refers to Address. And life time of Address is not managed by Employee. It is like"Employee has a Address". Let us see how it can be implemented in C#.
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() );
4. Composition - [Part of relationship]
Composition gives
us a 'part-of' relationship.
If we were going to
model a car, it would make sense to say that an engine is part-of a car. Within
composition, the lifetime of the part (Engine) is managed by the whole (Car),
in other words, when Car is destroyed, Engine is destroyed along with it. So
how do we express this in C#?
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.