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 中,Print1
即使它引用类型的对象,Print2
而在调用 2 中它的行为是对Print2
-object 的引用?为什么在 Call 2
print(B b)
中被调用Print2
而不是print(C c)
?
到目前为止,这对我来说是 Java 中最令人困惑的事情。谢谢您的帮助。