I came across the following 2 questions in Dan's mock exam(
http://www.danchisholm.net) on 'Type Conversions' topic.
Question 1
--------------------------------------------
class A {}
class B extends A {}
class C extends B {
static void m(A x, A y) {System.out.print("AA");}
static void m(A x, B y) {System.out.print("AB");}
static void m(B x, A y) {System.out.print("BA");}
static void m(B x, B y) {System.out.print("BB");}
public static void main(
String[] args) {
C c = new C();
m(c, c);
}
}
What is the result of attempting to compile and run the above program?
a. Prints: AA
b. Prints: AB
c. Prints: BA
d. Prints: BB
e. Compiler error.
f. Runtime error.
g. None of the Above
Answer is (d) Prints: BB
-------------------------------------------------
Question 4
class A {}
class B extends A {}
class C extends B {
static void m(A x, A y) {System.out.print("AA");}
static void m(A x, B y) {System.out.print("AB");}
static void m(B x, A y) {System.out.print("BA");}
static void m(B x, B y) {System.out.print("BB");}
static void m(A x, C y) {System.out.print("AC");}
public static void main(String[] args) {
C c = new C();
m(c, c);
}
}
What is the result of attempting to compile and run the above program?
a. Prints: AA
b. Prints: AB
c. Prints: BA
d. Prints: BB
e. Prints: AC
f. Compiler error.
g. Runtime error.
h. None of the Above
Answer is (f) Compiler error.
------------------------------------------------
After reading Dan's explanation for Q1, I thought I understood how most specific method is invoked. But after I did the second question I am confused. Can somebody explain me how the most specific method is chosen?
This is Dan's explanation for Q2:
-------------------------------------
"Section 15.12.2.2 of the
Java Language Specification states the following. 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. End of quote. In this case, no method is clearly more specific than all of the others. "
Thanks a lot,
Goutham.