Method Overloading is one of the types of polymorphism. In the object-oriented programming paradigm, polymorphism often refers to the ability to present the same interface for different forms. Although the concept of polymorphism is similar in all the programming languages, its implementation differs from language to language.
Method overloading is sometimes called static polymorphism or Compile Time Polymorphism or Early Binding. It basically means creating multiple methods in the same class with the same name but with different signatures. Here, different signatures refer to the total number of parameters passed to the functions & type.
Programming Example
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Overloading {
- class Car {
- public void Speed(int speed) {
- Console.WriteLine("Int: " + speed);
- }
- public void Speed(long speed) {
- Console.WriteLine("long: " + speed);
- }
- public void Speed(float speed) {
- Console.WriteLine("float: " + speed);
- }
- public void Speed(double speed) {
- Console.WriteLine("double: " + speed);
- }
- }
- class Program {
- static void Main(string[] args) {
- Car c = new Car();
- c.Speed(100);
- c.Speed(200 L);
- c.Speed(212.2 f);
- c.Speed(313.33);
- }
- }
- }
Output
Int: 100
long: 200
float: 212.2
double : 313.33
In the above example, you can see that there are four methods with the same name but the type of parameter or number of parameters is different. So, during its compilation time the compiler will check which method should be called.
Sometimes, we come across some tricky questions in an interview. I also faced one question about method overloading. The question was like the below one.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Overloading {
- class Car {
- public void Speed(int speed) {
- Console.WriteLine("Int: " + speed);
- }
- public void Speed(long speed) {
- Console.WriteLine("long: " + speed);
- }
- }
- class Program {
- static void Main(string[] args) {
- Car c = new Car();
- c.Speed(100);
- c.Speed(2147483647);
- c.Speed(2147483647 L);
- c.Speed(2147483648);
- }
- }
- }
Output
Int: 100
Int: 2147483647
long: 2147483647
long: 2147483648
From the above output, we can see that for the last value 2147483648, long function is called though it resembles the integer data type. It’s because Int32.MaxValue is equal to 2147483647 and so, instead of passing the value as integer data type, it gets passed as long data type.
Conclusion
This blog explained the concept of method overloading. I hope you liked it :). If you have any queries, please comment.
Thanks !!!!!