According to javadoc
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
My question is - is the order of parameters immaterial? In case that thay have same name and they are the same type as well?
In method overloading, the class can have multiple methods with the same name but the parameter list of the methods should not be the same. One way to make sure that the parameter list is different is to change the order of the arguments in the methods.
The order of the parameters make a difference because it is a different signature. Imagine you had a human signature and altered the order of the letters, it would no longer be the same signature.
The order matters, so two methods with the same arguments in different order are not considered to have the same signature. Save this answer.
The order matters, so two methods with the same arguments in different order are not considered to have the same signature.
For example, this example does not compile:
interface Foo {
void doIt(String what, int times);
}
class Bar implements Foo {
public void doIt(int times, String what) {}
}
The names of the parameters however, are irrelevant. This is perfectly fine:
interface Foo {
void doIt(String what, int times);
}
class Bar implements Foo {
public void doIt(String andNowForSomeThingCompetelyDifferent, int theLarch) {}
}
The Java Language Specification says the order is material, but it requires some teasing out to explain why:
8.4.1. Formal Parameters
The formal parameters of a method or constructor, if any, are specified by a list of comma-separated parameter specifiers.
...
8.4.2. Method Signature
Two method or constructor declarations M and N have the same argument types if all of the following conditions hold:
- They have the same number of formal parameters (possibly zero)
- They have the same number of type parameters (possibly zero)
- Let A1, ..., An be the type parameters of M and let B1, ..., Bn be the type parameters of N. After renaming each occurrence of a Bi in N's type to Ai, the bounds of corresponding type variables are the same, and the formal parameter types of M and N are the same.
...
Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.
The formal parameters are specified as a list, so for "the formal parameter types of M and N" to be the same, they must be the same list and lists are order-dependant.
Since the correspondance in 3 is order dependent, the order of type parameters also matters.
This becomes more obvious when you deal with the byte-code/JNI convention for Method Descriptors.
MethodDescriptor: ( ParameterDescriptor* ) ReturnDescriptor
Order must also be same else overriding will not happen
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With