I thought I understood the rules on which overriding method is called until I came across this question. I have expanded the original question to explain where my confusion is. When I run this, the output is ACC. I expected the output to be CCC. So I am confused about why method m1 in class A is called instead of m1 in class C.
I thought the relevant rule was that since the methods are not static and not private, the type of the object (not the type of the reference) would control where the
java runtime would begin its search for a matching method.
In other words, c1 is a type 'A' but the object is actually a type 'C' so I expected the call to go to method m1 in class C. The call to methods m2 and m3 seem to be using this rule but the call to m1 uses another rule that I don't understand.
class A {
void m1(A a) {System.out.print("A");}
void m2() {System.out.print("A");}
void m3(
String S) {System.out.print("A");}
}
class B extends A {
void m1(B b) {System.out.print("B");}
void m2() {System.out.print("B");}
void m3(String S) {System.out.print("B");}
}
class C extends B {
void m1(C c) {System.out.print("C");}
void m2() {System.out.print("C");}
void m3(String S) {System.out.print("C");}
}
class D {
public static void main(String[] args) {
A c1 = new C();
C c2 = new C();
c1.m1(c2);
c1.m2();
c1.m3("hello");
}}