Inheritance vs Composition in C#

CsharpProgrammingServer Side Programming

Inheritance

With Inheritance, you can designate that the new class should inherit the members of an existing class. This existing class is called the baseclass, and the new class is referred to as the derived class. Inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on.

For example, A base class Shape has a derived classes like Circle, Square, Rectangle, etc.

Composition

Under Composition, if the parent object is deleted, then the child object also loses its status. Composition is a special type of Aggregation and gives a part-of relationship.

For example, A Car has an engine. If the car is destroyed, the engine is destroyed as well.

Example

public class Engine {
   . . .
}
public class Car {
   Engine eng = new Engine();
   .......
}
raja
Published on 31-Aug-2018 11:07:02
Advertisements