use*_*361 5 java inheritance extends types
有人能解释一下这次执行的结果吗?我无法注意为什么调用每个方法.我们如何区分真实类型和表观类型.谢谢 :)
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;}
}
Run Code Online (Sandbox Code Playgroud)
结果:
Send a fax to A
Send an email to B
Send a fax to B
Run Code Online (Sandbox Code Playgroud)
您正在重载(根据维基百科),它创建了多个具有不同实现的同名方法。我认为你的意思是用方法覆盖该方法。重写(根据维基百科)允许子类或子类提供其超类或父类之一已提供的方法的特定实现。f(A x)f(B x)
根据您问题中表达的惊讶,我认为您想要类似的东西
@Override
public void f(A x) {
System.out.println("Send an email to"+ x ) ;
}
Run Code Online (Sandbox Code Playgroud)