I got a short question about polymorphism in java: Here are two class hierachies and the exercise is to tell what the the code is going to print out.
class All { /* ... */ }
class Most extends All { /* ... */ }
class Special extends Most { /* ... */ }
class Top {
public void m( All p ) { System.out.print("A "); }
}
class Middle extends Top {
public void m( All p ) { System.out.print("M "); }
public void m( Special p ) { System.out.print("L "); }
}
class Bottom extends Middle {
public void m( Most p ) { System.out.print("V "); }
public void m( Special p ) { System.out.print("X "); }
}
class Test {
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 );
x.m( special );
y.m( all );
y.m( special );
z.m( all );
z.m( most );
}
}
I pasted the code into an Eclipse .java file and it printed out 6x M, so M for each method. Could anyone help me understand?
Apparently the declared type of the argument of the calling reference and the argument matter and nothing else (according to the script) but in that case, why doesn't x.m(special) print out "L" since Special is the argument type of the method?
PS: My very first question on stackoverflow, really hope someone can help me understand :)
x.m(special)prints 'M' as x is the superclass reference variable (of Top class) that has no knowledge of what members are present in the Special class. But if you create an object ofMiddle m = new Middle;and then callm.m(special), you'll get L.x.m(special)print out "L"?"xis defined asTop x = ..., this means thatxcan chose only from method signatures available inToptype which gives us onlypublic void m( All p )signature. Polymorphism kiks in when JVM needs to find body of method with already selected signature, so here it will look at actual type of object held byxwhich isx = new Middle();and in theMiddleclass it will search for implementation forpublic void m( All p )method.