posted 23 years ago
Let me try to explain with rules in JLS 15.12 - method invocation. At complie time, we need determine method signature. According to JLS 15.12.2.2-choose the most specific method. Here are the rules:
If more than one method declaration is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
The precise definition is as follows. Let m be a name and suppose that there are two declarations of methods named m, each having n parameters. Suppose that one declaration appears within a class or interface T and that the types of the parameters are T1, . . . , Tn; suppose moreover that the other declaration appears within a class or interface U and that the types of the parameters are U1, . . . , Un. Then the method m declared in T is more specific than the method m declared in U if and only if both of the following are true:
T can be converted to U by method invocation conversion.
Tj can be converted to Uj by method invocation conversion, for all j from 1 to n.
So for your question:
case 1:
both method yy(int i) and (long i) are accessible and applicable. But here A can NOT convert to B although int i can convert to long i. Similarly, B can convert to A but long i can NOT convert to int i. Therefore, neither method is SPECIFIC to the other, you got ambiguous complie error.
case 2:
if you change b1.yy(3); to b1.yy(3L), only ONE method is applicable, it is yy(long i).
case 3: interesting one if you change B b1 = new B() to A b1 = new B(), ie.
you get result 3, because at compile time, type A (variable b1) has only ONE method applicable. If you now change the call to b1.yy(3L), you got compile error for method not found.
case 4: if you switch method in A and B, declare bi A;
you got output 3 although int parameter is passed, at compile time, only ONE method is applicable.
case 5: this is the case that one method is more specific than other
you got output 6. Because you have two method again applicable and B can convert to A and int i can convert to long i, B's method is more specific than A's. This is the same as you define two methods in same class in the example.
Overloaded method is choosen at compile time, overriden method at runtime, they are different.
hope this helps. please indicate if I am wrong.
[This message has been edited by Haining Mu (edited June 22, 2001).]
[This message has been edited by Haining Mu (edited June 22, 2001).]