I have an question about the following code (Is this call dynamic binding?). I feel confused about 3 point.
First, what is the mean of the variable pq? Does pd still be the data type of P or be the Q?
Second, when I invoke the pq.m(pp) method, why the result become Q::P but not P::Q?
Finally, what is this mean ((P) qq).m(qq);? I hope somebody could solve my problem.
The result of the following code will be
P::Q, Q::P, Q::Q, R::P, Q::P, Q::Q, Q::Q
class Test {
public static void main(String[] args) {
P pp = new P();
Q qq = new Q();
R rr = new R();
P pq = qq;
pp.m(qq);
pq.m(pp);
pq.m(qq);
rr.m(pp);
qq.m(pq);
qq.m(qq);
((P) qq).m(qq);
}
}
class P {
public void m(P p){System.out.println("P::P"); }
public void m(Q p){System.out.println("P::Q"); }
public void m(R c){System.out.println("P::R"); }
}
class Q extends P {
public void m(P p){System.out.println("Q::P"); }
public void m(Q p){System.out.println("Q::Q"); }
public void m(R c){System.out.println("Q::R"); }
}
class R extends Q {
public void m(P p){System.out.println("R::P"); }
public void m(Q p){System.out.println("R::Q"); }
public void m(R c){System.out.println("R::R"); }
}