我有类似这个设置的东西:
public class Base {
public String getApple() {return "base apple"};
}
public class Extended extends Base{
public String getApple() {return "extended apple"};
}
我在代码的其他地方有这个:
{
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??
}
我该如何实现?
最佳答案
首先:
if (b instanceof Extended){
b = (Extended) b;
}
什么都不做。你基本上是在说 b = b
,它什么也没说。您甚至没有更改引用。
其次,getApple()
将始终是动态绑定(bind)的,并且应该始终调用“扩展的苹果”——假定子类真正扩展了基类,并且该方法真正被重写。
基本上你需要做什么,以完成正确的 getApple()
行为:
- 删除 if 子句。它什么都不做。
- 确保你的类确实扩展了基类
- 确保
getApple()
方法覆盖基类方法。 (如果您不确定,请使用@override
注释)
关于Java继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1196208/