This question already has an answer here:
I've found resources that say method overloading is the ability for a language to use the same method with a different outcome, depending on context. Somehow, when I read other definitions, I fell like that's not the whole definition. Is there more to method overloading?
Is the ability of some languages to create methods/function with the same name but that differ for
input
/otput
parameters.A classical example is the class
constructor overloading
example in Java:You have a class with different constructors that accept different parameters, as you see they differ in their
signature
.That's just a very general way of describing it. Method overloading allows you to use a single method name, but "overload it" (provide more than one version) depending on "context" (which is typically the type or number of arguments passed in). Since each method is separate, they can cause a "different outcome".
For example, using C#, you can write:
First, you should know what is signature in programming. A signature of a function is its representation; the name of a function and its parameters determine its signature.
Overloading means changing the signature of a function to meet our needs.
Have a look at the following example:
Now, the function
sum()
can be called through two different ways: Either you can call it with two arguments or you can call it with three arguments. you have changed its signature to meet your needs. Instead of writing a separate function for two arguments, you put the load on the same function, that is why this is known as overloading.It's where you have a multitude of methods of the same name with different parameters.
Both can be called independently to one another with either
or
The context in this case is determined by the argument signature of the method, i.e. the number and type of the arguments.
For example:
The first method implementation would be an alternative to: