[英]Call own, non-overridden method
Say I have this code (not actually my code, but easier to understand):假设我有这段代码(实际上不是我的代码,但更容易理解):
public class A {
private int i1, i2;
protected int getSum() {
return i1 + i2;
}
protected int getSumTimes10() {
return getSum() * 10;
}
}
public class B extends A {
protected int getSum() {
throw new UnsupportedOperationException();
}
}
public class C extends B {
public void doSomething() {
// cannot call getSum();
System.out.println(getSumTimes10());
}
}
I overrive getSum()
in B
so that any class that extends B
cannot call it.我覆盖了B
中的getSum()
,因此任何extends B
的类都不能调用它。 However, I do need it in B
itself.但是,我确实需要它B
本身。
Calling doSomething()
on any C
will cause an UnsupportedOperationException
.在任何C
上调用doSomething()
都会导致UnsupportedOperationException
。
How can I make A
use its own getSum()
and not the overridden one so that I don't have to write the method twice?我怎样才能让A
使用它自己的getSum()
而不是被覆盖的,这样我就不必两次编写该方法?
The language itself doesn't give you any specific tools to be able to do that.语言本身并没有为您提供任何特定的工具来做到这一点。 While there exists super.someMethod()
to invoke a parent's implementation, there is no equivalent way to invoke a method which has the semantics that you're describing.虽然存在super.someMethod()
来调用父级的实现,但没有等效的方法来调用具有您所描述的语义的方法。
In the rare cases I've seen this be a desirable design choice, the usual workaround is to introduce a new method, possibly with some arbitrary prefix to make the name distinct, like do
.在极少数情况下,我认为这是一个理想的设计选择,通常的解决方法是引入一种新方法,可能带有一些任意前缀以使名称与众不同,例如do
。
public class A {
private int i1, i2;
protected int getSum() {
return doGetSum(); // delegate to non-overrideable version
}
protected int getSumTimes10() {
return doGetSum() * 10; // delegate to non-overrideable version
}
private int doGetSum() {
return i1 + i2;
}
}
Your base class can rely on the do___
version in cases where the overridden version would be undesirable and you never have to duplicate the implementation.您的基类可以依赖do___
版本,以防不希望被覆盖的版本并且您永远不必复制实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.