About Lesson
Inheritance and polymorphism
Inheritance and polymorphism are two important concepts in object-oriented programming that are closely related. Let’s explore them:
Inheritance:
- Inheritance is a mechanism that allows a class (derived class) to inherit the properties and methods of another class (base class).
- The derived class extends the base class, acquiring its members and functionalities.
- In C#, inheritance is achieved using the : symbol, followed by the name of the base class.
Example:
class Shape
{
public virtual void Draw()
{
Console.WriteLine(“Drawing a shape”);
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine(“Drawing a circle”);
}
}
Polymorphism:
- Polymorphism is the ability of an object to take on different forms, depending on the context.
- In the context of inheritance, polymorphism allows objects of a derived class to be treated as objects of their base class.
- This enables the use of base class references to invoke overridden methods or access common properties.
- Polymorphism allows for code flexibility, extensibility, and the implementation of “code once, use many times” principles.
Example:
Shape shape1 = new Shape();
Shape shape2 = new Circle();
shape1.Draw(); // Output: “Drawing a shape”
shape2.Draw(); // Output: “Drawing a circle”