问题
I am trying to do some polymorphism exercises and I cannot figure out how this kind of polymorphism works. I did not find any deep information about this kind of exercised. I hope you guys could give me some explanation.
exercise 1:
class Top {
public void m( Middle p ) System.out.print("A ");
}
class Middle extends Top {
public void m( Object p ) System.out.print("M ");
public void m( Middle p ) System.out.print("L ");
}
class Bottom extends Middle {
public void m( Object p ) System.out.print("V ");
public void m( Middle p ) System.out.print("X ");
}
class Test {
public static void run() {
Top tm = new Middle();
Middle mb = new Bottom();
tm.m (mb); -> L
tm.m(new Bottom()); -> L why?
mb.m(mb); -> X
mb.m(tm); -> V why?
mb.m(new Middle()); -> X
new Bottom().m(tm); -> V
}
}
exercise 2:
class Top {
public void gg( Top o ) System.out.print("A ");
public void gg( Middle m ) System.out.print("B ");
}
class Middle extends Top {
public void gg( Top o ) System.out.print("L ");
public void gg( Bottom b ) System.out.print("M ");
}
class Bottom extends Middle {
public void gg( Top o ) System.out.print("X ");
public void gg( Middle m) System.out.print("Z ");
}
class Test {
public static void run() {
Top oo = new Top();
Top ff = new Middle();
Bottom uu = new Bottom();
oo.gg(ff); -> A
oo.gg(uu); -> A why?
ff.gg(ff); -> L
ff.gg(uu); -> B why?
uu.gg(ff); -> X
uu.gg(uu); -> X why?
}
}
Thank you in advance!
Greets
回答1:
In all of these cases, the methods that can be considered depend on the compile-time type of the variable, but the method that is actually called depends on the runtime type of the object. So for
Top ff = new Middle();
the methods of Middle
are the ones that will be called - but these may be inherited from Top, and we can only call methods that are available in Top
at compile time, because ff
is declared as a Top
.
To determine which of the overloaded methods is called, we look at the parameter type, and choose the most specific method. So if we have to choose between:
public void m( Object p ) System.out.print("M ");
public void m( Middle p ) System.out.print("L ");
and we are passing a Bottom
, then the second method will be chosen. You can think of Bottom
as being closer to Middle
than Object
in the class hierarchy:
Bottom -> Middle -> Top -> Object
Finally, some of your answers are just wrong (exercise 2) - I suggest you try running the code, which may need a bit of tweaking so it actually compiles.
oo.gg(uu); // -> A why? -- actually produces B
uu.gg(uu); // -> X why? -- actually produces M
来源:https://stackoverflow.com/questions/28809274/java-polymorphism-late-binding-rules