Inheritance, Composition and Aggregation in C#
1. Inheritance
In real life, inheritance is the action of passing property, debts or rights of parents to their children. Similarly, in programming, inheritance is the ability of a class to “copy” or acquire all properties and methods from another class. The class inheriting from another is a child class or derived class, and the class inherited by another class is the parent class. The inheritance helps derived classes extend their functionality as well as type, and create an “is-a” relationship between parent and child classes.
For example:
The above example illustrates that Fighter is a parent class and Soldier is a child class. In the child class, you do not need to repeat all attributes and methods defined in the parent class. Apparently, the Soldier “is-a” Fighter. Let me create instances of them and make a call to GetLife() method.
2. Composition and Aggregation
Composition and aggregation are programming techniques which allow a class to “contain” one or more objects of other classes to form a big object doing some specific functionalities. The container is the superclass and the classes contained by the superclass are subclasses. Therefore, the superclass and subclasses have a “has-a” relationship.
However, composition and aggregation must have some differences to distinguish between them. Let’s see the following examples:
Composition:
Aggregation
The two examples above show “has-a” relationship, DinnerTable “has-a” Chair around and Chair “has-a” ChairLeg (obviously, a chair has 4 four legs, but here is just an example for you to understand the concept). Therefore, DinnerTable has a loose relationship with Chair because DinnerTable can not be useless or destroyed if it does not have a Chair object. In other words, DinnerTable exists independently from Chair. However, oppositely, Chair has a solid relationship with ChairLeg, which means that Chair cannot exist independently without ChairLeg.
As a result, the main difference is independence. In composition, subclasses' life cycle depends directly on superclass’s life cycle and vice versa. In aggregation, the subclasses and superclass have their own life cycle.
3. Conclusion
This post is a brief explanation of inheritance, composition and aggregation in object-oriented programming for beginners. If you find any mistakes in my post or give my feedback, please comment below. I am welcome to your responses.
Last updated