我在 Java有问题。 我的方法可以扩大。 问题在于,这种方法指其他类别方法,也可以推广。
Consider the following class:
public class Foo {
protected int xLast;
public updateMe(int x, int y) {
updateX(x);
}
protected updateX(int x) {
this.xLast = x;
}
}
班级延长如下:
public class Bar extends Foo {
protected int xAverage = 0;
protected int xCount = 0;
protected int y;
public updateMe(int x, int y) {
super.updateMe(x, y);
updateX(x);
updateY(x);
}
protected updateX(int x) {
this.xAverage = (this.xAverage * this.xCount) + x;
this.xCount++;
this.xAverage /= xCount;
}
protected updateY(int y) {
this.y = y;
}
}
也是按这一类别:
public class Abc extends Foo {
}
当我做以下工作时:
Foo myBar = new Bar();
myBar.updateMe(1, 2);
<代码>Foo.updateX 无需使用<代码>Bar.updateX方法。 有一些解决办法,有些办法没有效果,或者很简单:
- In
Bar.updateX
callsuper.updateX
. This will cause bothupdateX
methods to be called twice. - Remove the
updateX
call inFoo.updateMe
, forcing the extending classes to callsuper.updateX
. This will cause the classAbc
to have useless code that it doesn t need, or else the Abc class will not callupdateX
at all. - Rename the methods so that they do not override each other. This will work, but is not safe (in the future this might be forgotten and lead to problems) and is not enforced by the language.
我知道,这在一定程度上属于法典范畴,但我看不到这样做的更好办法。
Basically I am looking to do something like this: in Foo.updateMe
I would like to call Foo.updateX
specifically, and not just the polymorph-ed updateX
.
我认为,像<代码>新代码”这样的东西。 C#中的关键词可以解决我的问题,但 Java似乎有某种或另一种方式可以做到这一点。
<><>Edit>:
最后,我选择重新命名犯罪方法。 我只有一个办法造成这一问题,这里建议的解决办法是,尽管从设计观点看,这一特定法律将更难以理解和维持。