Difference between Overloading and Overriding ?

Overloading:

Overloading refers to the ability to define multiple methods in the same class with the same name but different parameters. The compiler differentiates between these methods based on the number or types of parameters. Here’s an example:

public class Example
{
    public void PrintSum(int a, int b)
    {
        Console.WriteLine($"Sum: {a + b}");
    }

    public void PrintSum(int a, int b, int c)
    {
        Console.WriteLine($"Sum: {a + b + c}");
    }
}

In this example, we have two methods named PrintSum. One takes two integers, and the other takes three. The compiler determines which method to call based on the number of arguments provided.

Overriding:

Overriding is a concept related to inheritance and polymorphism. It occurs when a derived class provides a specific implementation for a method that is already defined in its base class. To override a method, both the base and derived methods must have the same method signature. Here’s an example:

public class BaseClass
{
    public virtual void Greet()
    {
        Console.WriteLine("Hello from BaseClass");
    }
}

public class DerivedClass : BaseClass
{
    public override void Greet()
    {
        Console.WriteLine("Hello from DerivedClass");
    }
}

In this example, DerivedClass inherits from BaseClass, and it overrides the Greet method. When an instance of DerivedClass calls the Greet method, it uses the overridden implementation.

To summarize:

  • Overloading involves defining multiple methods with the same name but different parameters within the same class.
  • Overriding occurs when a derived class provides a specific implementation for a method that is already defined in its base class.

Comments

Popular posts from this blog

How do I calculate a MD5 hash from a string?

What is WSDL?