What is the difference between method overloading and method overriding?

10 minintermediateOOPpolymorphismmethods

Quick Answer

Method overloading is compile-time polymorphism where multiple methods have the same name but different parameters (signatures). Method overriding is runtime polymorphism where a derived class provides a new implementation of a virtual/abstract method from the base class. Overloading is resolved at compile-time, overriding at runtime.

Detailed Answer

Method Overloading occurs when multiple methods in the same class have the same name but different parameters (different number, type, or order of parameters). It's a compile-time polymorphism.

Method Overriding occurs when a derived class provides a specific implementation of a method that is already defined in its base class. It's a runtime polymorphism.

Example:

// Method Overloading
public class Calculator
{
    // Same method name, different parameters
    public int Add(int a, int b)
    {
        return a + b;
    }
    
    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }
    
    public double Add(double a, double b)
    {
        return a + b;
    }
}

// Method Overriding
public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Some generic animal sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}

// Usage
var calc = new Calculator();
calc.Add(5, 10);        // Calls first method
calc.Add(5, 10, 15);    // Calls second method

Animal myDog = new Dog();
myDog.MakeSound();      // Outputs: Woof!