Inheritance And Polymorphism

Lesson 3.4: Basic Inheritance and Polymorphism Concepts


In previous lessons, you've created classes and objects. Now, let's explore how classes can relate to each other through inheritance, and how this relationship enables polymorphism.


Inheritance: Building Upon Existing Classes


Inheritance allows you to create a new class (derived class or child class) that inherits properties and methods from an existing class (base class or parent class).

This means the derived class automatically gets all the features of the base class and can add its own unique properties and methods.

Think of inheritance as a family tree – the derived class is a specialized version of the base class.

Syntax for Inheritance:


C#

class DerivedClass : BaseClass 

{

    // Additional properties and methods specific to DerivedClass

}

Example: Animal Inheritance


C#

class Animal

{

    public string Name { get; set; }

    public virtual void MakeSound() // Virtual method

    {

        Console.WriteLine("Generic animal sound");

    }

}


class Dog : Animal

{

    public override void MakeSound() // Overriding method

    {

        Console.WriteLine("Woof!");

    }

}


class Cat : Animal

{

    public override void MakeSound()

    {

        Console.WriteLine("Meow!");

    }

}

Polymorphism: Many Forms


Polymorphism means "many forms." In OOP, it refers to the ability of different objects to respond to the same method call in their own unique way.

In our example, both Dog and Cat objects have a MakeSound() method, but they produce different sounds when the method is called. This is polymorphism in action.


Virtual and Override Keywords


The virtual keyword in the base class indicates that a method can be overridden in derived classes.

The override keyword in the derived class signifies that a method is intended to replace the base class's implementation.


Why Inheritance and Polymorphism?


Code Reusability: Avoid duplicating code by inheriting common functionality.

Extensibility: Easily add new features by creating specialized derived classes.

Flexibility: Treat objects of different classes interchangeably through their common base class.


Hands-On Exercise:


Create a Shape base class with properties for Color and a method CalculateArea().

Create derived classes like Circle, Rectangle, and Triangle that inherit from Shape.

Override the CalculateArea() method in each derived class to implement the specific area calculation logic.

Create objects of different shapes and call the CalculateArea() method to demonstrate polymorphism.

This exercise will help you solidify your understanding of inheritance and polymorphism in C# and how they promote flexible and reusable code.

Course Syllabus