Association, Aggregation, and Composition
Inheritance is an (Is-A) Relationship.
+ Inherited publicly
+ Inherited protectively
+ Inherited privately
(e.g. A dog is inherited from the parent class animal)
Object Orienting Programming mimics real-world objects.
When we consider real-world objects, the most complicated thing that arises is relationships. How to deal with the relationships among other classes.
1) A manager (is a) type of employee. ~Inheritance
2) Manager (has a) swipe card to enter the company premises. ~Association
3) He has many workers under him. ~Aggregation
4) His salary depends on project success. ~Composition
5) Project success depends on a manager. ~Composition
Association depicts the relationship between two classes.
Both of the classes are not dependent on each other.
They can exist independently. If one is broken, it doesn’t mean the other one also has to be broken.
Association can be categorized into:
Aggregation (Weak Association) (HAS-A Relationship)
The sub-classes can’t belong to any other base class. Subclasses can stay happily without the base class itself. Classes can exist independently.
A car and driver have loose coupling in between them.
Why because a car can exist without a driver and a driver can exist without the car.
Hence they are not tightly coupled.
A car can have a driver, but it will still remain a car without the driver driving the car.
A basketball team consists of many players and player can be part of many teams, (in the case of the franchise dealership)
A team can exist without one basketball player (there can be a list of players) and a basketball player can exist without being in a specific team.
So they are not tightly coupled but are loosely coupled.
This is how you depict aggregation.
Composition (Strong Association)(Containment, part-whole, Has-a Relationship) (part of the relationship)
When both of the classes are dependent on each other, such kind of relationship is called a composition relationship.
If one goes down, the other will also go down.
They are dependent on each other. Not like aggregations.
Key-word to remember: it is composed in the other class. One class is part of another class (dependent on each other)
(e.g.) Car has an engine. The engine is a part of the car. They are tight coupling. An engine can’t exist without a car. Every car depends on its engine.
The life of the engine is only until the car is present. The car dies, the engine will also die.
The code snippet is identical to the aggregation example;
Logically the engine cannot exist without the car.