public class Print1 {
int x = 1;
public void print(A a) { System.out.println(x); }
public void print(B b) { System.out.println(x+1); }
}
public class Print2 extends Print1 {
int x = 3;
public void print(A a) { System.out.println(x); }
public void print(B b) { System.out.println(x+1); }
public void print(C c) { System.out.println(x+2); }
}
// a tester class with main method
A a = new A(); B b = new B(); C c = new C();
Print1 p1 = new Print1();
Print2 p2 = new Print2();
p1 = p2;
System.out.println(p1.x); // Call 1, p1 is from Type Print1
p1.print(c); /* Call 2
//p1 is from Type Print2, print(B b) will be called */`
クラス B はクラス A のサブクラスであり、C は B のサブクラスです。
タイプのオブジェクトを参照しているのに
P1
タイプからのコール1で、コール2でオブジェクトへの参照として動作しているのはなぜですか?Print1
Print2
Print2
なぜ Call 2
print(B b)
は fromPrint2
ではなく from で呼び出されるのprint(C c)
ですか?
これは、これまでJavaで最も混乱していたことです。ご協力ありがとうございました。