有人能解释一下这个执行结果吗?我无法注意到为什么会调用每个方法。我们如何区分真实类型和表面类型。谢谢 :)
public class JavaApplication15 {
public static void main(String[] args) {
A a = new A();
B b= new B();
A ab = new B();
b.f(a);
b.f(b);
b.f(ab);
}
}
public class A {
private final String id="A";
public void f(A x){
System.out.println("Send a fax to "+ x ) ;
}
public String toString(){return id;}
}
public class B extends A{
private final String id="B";
public void f(B x){
System.out.println("Send an email to"+ x ) ;
}
public String toString(){return id;}
}
结果:
Send a fax to A
Send an email to B
Send a fax to B