Java,隐式调用重写方法 [英] Java, Call overridden method implicitly
问题描述
现在在某些Java代码中我有这样的东西
Right now in some Java code I have something like this
class A {
void f() {
}
A() {
f();
}
}
class B extends A{
@Override
void f() {
//do some stuff
super.f();
}
}
class C extends B {
@Override
void f() {
//do some stuff
super.f();
}
}
我想要 f ()
调用然后向上遍历每个父类,运行重写的 f()
。我通过显式调用 super.f()
来做到这一点,虽然我不想这样做。
I want to have f()
called and then iterate upwards through each parent class, running the overridden f()
. I do this by calling super.f()
explicitly, although I'd like to not have to do this.
我这样做的原因是必须在到达A中的构造函数之后进行后处理。并且每个类中都有状态正确初始化,这就是为什么我们有 f()
的向上痕迹。
The reason why I do this is there post processing that must be done after the constructor in A is reached. And there is state in each class that much be properly init'd, which is why we have the upward trace of f()
's.
所以 A
的构造函数实际上是
So the constructor of A
is really
A() {
//init some state in a
f(); //run f(), which will depend on the previous operation
}
如果我做类似 new C();
我想要 Cf()
调用,然后 Bf( )
调用,然后 Af()
调用
If I do something like new C();
I want C.f()
called, then B.f()
called, then A.f()
called
无论如何,如果有更智能的话这样做的方式,我很开放。
Anyway, if there is a smarter way of doing this, I'm open to it.
推荐答案
在构造函数中调用非final方法通常是一个坏主意 - 至少,我建议你记录严重。请记住,当调用f()时,不会调用C的构造函数 - 也不会调用任何变量初始值设定项。该对象只是半初始化,因此需要非常仔细地编写方法。
Calling non-final methods in a constructor is generally a bad idea - at the very least, I'd suggest you document it heavily. Bear in mind that when f() is called, C's constructor won't have been called - and neither will any variable initializers. The object is only half-initialized, and so methods will need to be written very carefully.
没有办法隐式调用 super.f( )
虽然在正常的Java中。鉴于我将围绕该代码发出大量警告,单个陈述远离世界末日:)
There's no way of implicitly calling super.f()
though in normal Java. Given the large warnings I'd be putting around that code, a single statement is far from the end of the world :)
如果你想验证它是否被调用,您可以随时在A的构造函数中检查 Af()
的结果 - 这将检查呼叫是否已达到最高级别。
If you want to verify that it's called, you could always check for the results of A.f()
in A's constructor immediately after the call - that will check that the call has reached the top level.
这篇关于Java,隐式调用重写方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!