Can someone please explain how the compiler/runtime runs the
appropriate method in the example?
There are 6 classes and a method void m(/* ... */)
with different parameters.
I know that the compiler analyses the
declared types.
The output is always "M" from the Middle class.
public class All {}
public class Most extends All {}
public class Special extends Most {}
public class Top {
public void m( All p ) { System.out.println("A"); }
}
public class Middle extends Top {
public void m( All p ) { System.out.println("M"); }
public void m( Special p ) { System.out.println("L"); }
}
public class Bottom extends Middle {
public void m( Most p ) { System.out.println("V"); }
public void m( Special p ) { System.out.println("X"); }
}
public class Main {
public static void main(String[] args) {
All all = new All();
Most most = new Most();
Special special = new Special();
Top x = new Middle();
Top y = new Bottom();
Middle z = new Bottom();
x.m( most ); // Output is M
x.m( special ); // Output is M
y.m( all ); // Output is M
y.m( special ); // Output is M
z.m( all ); // Output is M
z.m( most ); // Output is M
}
}