Both Method overloading and overriding are one of the strong features in object-oriented programming languages.
In a class when you have two methods performing similar functionality but they just require different signatures or types then you can overload them instead of giving them a new name. On the other hand, if your class method does not fulfill the required functionality, you can derive a new class from this base class and update the methods functionality in the derived class using overriding.
Lets see how this can be achieved and also understand their differences.
Method Overloading
a. Overloading means providing different function implementation with same name but with different signatures(return type and input arguments). Both the functions should be declared with the overload keyword.
b. Method overloading is done in the same class. Depending on the argument passed, .net picks up the respective function accordingly.
public class()
{
void myFunction(int i);
void myfunction(string s);
}
c. Overloading is resolved at compile time.
Method Overriding
a. Overriding means providing different function implementation in the derived class with same name and same signature. Overriding allows you to change the behaviour of the function in the child/derived class.
b. You can override a method in the derived class only if you declare the function as virtual in the base class. Method overriding is done in different classes - base class and derived class.
Base Class function
public virtual void myFunction();
Derived Class function
public override void myFunction();
c. Overriding is resolved at runtime.
Difference between Method Overloading and Overriding
Posted by Techie Cocktail | 9:56 AM | C-Sharp | 1 comments »
Subscribe to:
Post Comments (Atom)
Nicely explained. Thanks.