What is the difference between Overloading and Overriding?

Overloading and overriding are two essential concepts in object-oriented programming. Let's understand the difference between them with examples:

Method Overloading (Compile-time Polymorphism): Method overloading allows a class to have multiple methods with the same name but different signatures (different number or types of parameters). The compiler determines which method to call based on the method signature during compile-time.

Example of method overloading in C#:

public class Calculator { // Overloaded method for adding two integers public int Add(int a, int b) { return a + b; } // Overloaded method for adding three integers public int Add(int a, int b, int c) { return a + b + c; } // Overloaded method for adding two doubles public double Add(double a, double b) { return a + b; } }

In this example, the Calculator class has three methods named Add, but each method has a different set of parameters. The compiler resolves the method call based on the number and types of arguments passed during the method call.

Method Overriding (Runtime Polymorphism): Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameter list as the method in the superclass. The method to be executed is determined at runtime based on the actual object's type.

Example of method overriding in C#:

public class Animal { public virtual void MakeSound() { Console.WriteLine("Animal makes a sound"); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Dog barks"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Cat meows"); } }

In this example, the Animal class has a virtual method MakeSound(), and the Dog and Cat classes override this method with their specific implementations. When you call the MakeSound() method on an instance of Dog or Cat, the appropriate overridden version of the method is executed based on the actual object's type.

To summarize, method overloading is about having multiple methods with the same name but different signatures in the same class, and the decision of which method to call is made by the compiler during compile-time. Method overriding is about providing a specific implementation for a method in a subclass that is already defined in its superclass, and the decision of which method to call is made at runtime based on the actual object's type.

Post a Comment

Previous Post Next Post