In many programming languages like C# and Java the same method can be declared in few variants with the same name and different parameters. This goes by the term “method overloading”. Now let's see how to write these overloaded methods.
In programming the way you can identify a method is through the couple of elements of its declaring – name of the method and a list containing its parameters. These two elements determine its specification, the so invoked signature of the method.
In this example the methods signature is its name (
If our program has methods with the same names, but with different signatures, we can say that we have method overloading.
As we mentioned, if you use the same name for several methods with different signatures, this means that you are overloading a method. The code below shows how three different methods can use the same name, but have different signatures and execute different actions.
It is important to say that the return type as a result of the method is not a part of its signature. If the return type was a part of the signature, then the compiler doesn't know which method exactly to invoke.
Let's look at the following example - we have two methods with different return types. Despite that Visual Studio shows that there is a mistake, because both of their signatures are the same. Therefore when trying to invoke a method named
Print(…), the compiler can't know which of the two methods to run.
The input is two values of the same type. The values can be of type
string. Create a method
GetMax(), which returns as a result the greater of the two values.
We need to create three methods with the same name and different signatures. First we create a method, which will compare integers.
Following the logic of the previous method we create another one with the same name, but this one will compare characters.
The next method we need to create will compare strings. The logic here is a bit different from the previous two methods because variables of type
string can not be compared with the operators
>. We will use the method
CompareTo(…), which returns a numerical value: larger than 0 (the compared object is larger), smaller than 0 (the compared object is smaller) and 0 (the two objects are the same).
The last step is to read the input data, to use the appropriate variables and to invoke the method
GetMax() from the body of the
Test your solution here: https://judge.softuni.bg/Contests/Practice/Index/594#6.