In this code …
public class Person { public void walk(String alpha, int beta) {} public void walk(int beta, String alpha) {} }
… I am just changing the order of parameters, but it is still considered as method overloading, i.e. static binding at compile time. My questions are:
- Why order is considered to be part of a method’s signature in Java?
- What are the advantages? From my POV I do not see the exact advantage in doing so.
Advertisement
Answer
Because “having lunch first and jogging afterwards”, and “jogging first and having launch afterwards”, are two different patterns, even though they only differ in order.
In Java, we have a concept of Method Overloading, which says, that in one class, you are able to define methods with the same name, as long as their signatures will be different.
Now let’s reformulate above “jogging/lunch” example, into more formal and Java-related concepts:
When you have overloaded methods, JVM needs some way to understand which particular overloaded method to invoke, using the name that identifies more than one methods; and it knows that, thanks to the type, number, and the order of the method parameters.
Type, only, is not enough information, because if Java dismisses the order for matching parameters and their respective arguments, it will not be clear which particular method to call.
Imagine you define foo(int a, char b)
and foo(char a, int b)
, and you somewhere, invoke .foo([...])
. How do you think, based on what compiler should decide which method call to compile for this code? (compiler won’t let you through, if you violate signature);
Furthermore – how the JVM should do the binding, later, at runtime, when the foo
is invoked, but there are, at least, two methods, defined with the same name?
For this, methods have signatures, where the order of parameters, exhibiting distinct patterns, gives the ability, to Java machine, to proceed with a correct and appropriate bindings and calls.
Also, think about varargs, in the hypothetical scenario, where order of the parameters does not matter.
Do you think:
foo(String... a, String b)
and
foo(String b, String... a)
will be same?
If you do, you are wrong.
In the layman’s terms, it gets difficult to parse the input pattern – how many of the input string literals, method of the first signature, should consider to accept, as an array argument, in its first parameter (only first literal? first two ones?.. how many? where the array ends?), and which string argument, particularly, should be accepted into the second parameter (for a more in depth explanation, see this); therefore, you will have a compile time error:
error: varargs parameter must be the last parameter
While in the second case, disregarding of how many strings you will call this method with, first argument will be always bound to the first parameter, and the rest will be constituting an array, passed as an argument, into the second parameter.