所以,问题来了。假设我有以下代码流程:
public class SomeGrandparent {
private int x;
private int y;
...
public void setX(int x) {setting value of x...}
public void setY(int y) {setting value of y...}
}
public class SomeParent extends SomeGrandparent {
...
public void move() {manipulate object movement via calls to inherited setX and setY}
}
public class SomeChild extends SomeParent {
...
public void setX(int x) {throw exception} //Override method. Child should not be allowed to directly modify X.
public void setY(int y) {throw exception} //Override method. Child should not be allowed to directly modify Y.
}
然后,在程序的后面,我有以下内容:
SomeChild aChild = new SomeChild();
...
aChild.move();
执行后,当调用 aChild.move()
时,会抛出错误。为什么在 SomeChild
中,继承的 move()
方法使用本地重写的 setX 和 setY 方法?有什么方法可以让 aChild.move()
调用 SomeParent 中定义的 move() 并使用 SomeParent 中定义的 setX 和 setY 吗?
即使我在 SomeChild 中明确定义了以下内容,
...
public void move() {
super.move();
}
然后aChild.move()
仍然使用SomeChild
中本地重写的setX和setY。这让我抓狂。任何帮助表示赞赏。
我能理解的唯一解决方案是复制 SomeParent 的 move() 方法中的所有代码并将其粘贴到 SomeChild 中,将其对 setX 和 setY 的所有引用替换为 super.setX 和 super.setY 。然而,这完全违背了继承的初衷!
最佳答案
多态性将选择对象的运行时类型来调用 setX
和 setY
,即使它们是在不重写这些方法的父类(super class)中调用的。
您可以在 SomeGrandparent
中创建方法 setX()
和 setY
final
,以便子类如 SomeChild
无法覆盖它们。
关于java - 当子类在本地重写其中一些方法时,如何强制子类使用父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28776213/