Sobes.tech
Junior

What is inheritance and polymorphism in reference data types?

sobes.tech AI

Answer from AI

Inheritance is a mechanism that allows creating new classes (derived or subclasses) based on existing ones (parents or superclasses), inheriting their properties and methods. This promotes code reuse and the creation of class hierarchies.

Polymorphism is the ability to treat objects of different classes that belong to the same inheritance hierarchy as objects of their common ancestor. This allows calling the same method on objects of different types, with the behavior of the method depending on the specific type of the object.

Example of inheritance in C#:

public class Animal
{
    public string Name { get; set; }

    public virtual void MakeSound() // Virtual method for polymorphism
    {
        Console.WriteLine("Generic animal sound");
    }
}

public class Dog : Animal // Dog class inherits from Animal
{
    public string Breed { get; set; }

    public override void MakeSound() // Override parent method
    {
        Console.WriteLine("Woof!");
    }
}

Example of polymorphism in C#:

Animal myDog = new Dog(); // Dog object is treated as Animal
myDog.Name = "Sharik";
myDog.MakeSound(); // Calls the MakeSound method from the Dog class (Woof!)

Animal genericAnimal = new Animal();
genericAnimal.Name = "Unknown";
genericAnimal.MakeSound(); // Calls the MakeSound method from the Animal class (Generic animal sound)

Inheritance and polymorphism are key principles of object-oriented programming and are widely used in reference data types to build flexible and extensible systems.

What is inheritance and polymorphism in reference… - sobes.tech