Explain polymorphism in detail, including method overloading and overriding.

Polymorphism allows objects of different classes to be treated as objects of a common type.

Method Overloading:

  • Defining multiple methods with the same name but different parameters within the same class.
public class Calculator
{
    public int Add(int a, int b) { return a + b; }
    public double Add(double a, double b) { return a + b; }
    public string Add(string a, string b) { return a + b; }
}

Method Overriding:

  • Providing a new implementation for an inherited method in a derived class.
public class Animal
{
    public virtual string MakeSound() { return "Generic animal sound"; }
}

public class Dog : Animal
{
    public override string MakeSound() { return "Woof!"; }
}

public class Cat : Animal
{
    public override string MakeSound() { return "Meow!"; }
}

//Usage
Animal myDog = new Dog();
Animal myCat = new Cat();
Console.WriteLine(myDog.MakeSound()); // Output: Woof!
Console.WriteLine(myCat.MakeSound()); // Output: Meow!
  • The virtual keyword in the base class allows derived classes to override the method. The override keyword in the derived class indicates that it’s providing a new implementation.

Leave a Reply

Your email address will not be published. Required fields are marked *