Java继承问题

hdx*_*hdx 1 java inheritance

我有类似于这个设置:

public class Base {
    public String getApple() {return "base apple"};
}

public class Extended extends Base{
    public String getApple() {return "extended apple"};
}
Run Code Online (Sandbox Code Playgroud)

代码中的其他地方我有这个:

{
    Base b = info.getForm();

    if (b instanceof Extended){
        b = (Extended) b;
    }

    System.out.println(b.getApple()); // returns "base apple" even when if clause is true why??

}
Run Code Online (Sandbox Code Playgroud)

我该如何做到这一点?

Yuv*_*dam 6

第一:

if (b instanceof Extended){
    b = (Extended) b;
}
Run Code Online (Sandbox Code Playgroud)

什么都不做.你基本上是说b = b,什么也没说.你甚至没有改变参考.

其次,getApple()将始终动态绑定,并且应始终调用"扩展的apple" - 假定子类真正扩展了基类,并且该方法被真正覆盖.

基本上你需要做什么,以实现正确的getApple()行为:

  • 删除if子句.它什么都不做.
  • 确保你的类确实扩展了基类
  • 确保该getApple()方法重写基类方法.(@override如果您不确定,请使用注释)

  • 但它仍然没有改变...... if子句没有任何效果. (3认同)