假设我有这样声明的类:
public abstract class IdentifiableEntity {
public boolean validate() {
return true;
}
}
public class PreferenceCategory extends IdentifiableEntity {
public boolean validate() {
return true;
}
}
现在,假设我创建了 PreferenceCategory 变量,我想调用 IdentifiableEntity.validate() 方法,不是 PreferenceCategory.validate() 方法。
我原以为我可以用强制转换来做到这一点(见下文),但它仍然调用重写的方法:
PreferenceCategory cat = new PreferenceCategory();
// this calls PreferenceCategory.validate(), not what I want
((IdentifiableEntity)cat).validate();
有什么办法吗?
最佳答案
你不能。最好的办法是向 PreferenceCategory
添加另一个方法,它调用 super 的 validate()
方法。
public boolean validateSuper() {
return super.validate();
}
但是你为什么要这样做呢?这有点设计味道。您可能会发现 chain of responsibilty pattern有趣。
关于java - 如何调用基类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3804204/