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