Mark As Completed Discussion

Inheritance and Polymorphism

Inheritance and polymorphism are important concepts in object-oriented programming. In C#, inheritance allows a class to inherit the properties and methods of another class, while polymorphism allows an object to take on different forms.

Inheritance

Inheritance provides a way to create a new class based on an existing class. The new class, called the derived class or subclass, inherits the properties and methods of the existing class, called the base class or superclass. This enables code reuse and promotes the principle of DRY (Don't Repeat Yourself).

TEXT/X-CSHARP
1// Base class
2public class Animal
3{
4    public virtual void MakeSound()
5    {
6        Console.WriteLine("The animal makes a sound.");
7    }
8}
9
10// Derived class
11public class Dog : Animal
12{
13    public override void MakeSound()
14    {
15        Console.WriteLine("The dog barks.");
16    }
17}

In this example, we have a base class called Animal with a method MakeSound(). We also have a derived class called Dog that inherits from the Animal class and overrides the MakeSound() method to make the dog bark. By creating a new instance of the derived class, we can access both the inherited methods from the base class and the overridden methods specific to the derived class.

Polymorphism

Polymorphism allows an object to take on many forms. In the context of inheritance, it means that a variable of a base class type can refer to an object of a derived class type. This allows us to write code that works with objects of different derived classes through a common base class interface.

TEXT/X-CSHARP
1// Using inheritance and polymorphism
2Animal animal = new Animal();
3animal.MakeSound(); // Output: The animal makes a sound.
4
5Animal dog = new Dog();
6dog.MakeSound(); // Output: The dog barks.

In this example, we create an instance of the Animal class and call the MakeSound() method. The output is "The animal makes a sound." Then, we create an instance of the Dog class and assign it to a variable of type Animal. When we call the MakeSound() method on the dog variable, the output is "The dog barks." This is possible because the dog variable, although of type Animal, actually refers to an object of type Dog, and the overridden method in the Dog class is called.

In summary, inheritance allows classes to inherit properties and methods from other classes, promoting code reuse. Polymorphism allows objects to take on different forms, enabling flexibility and extensibility in object-oriented programming.

C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment