Java, Call overridden method implicitly

后端 未结 3 898
耶瑟儿~
耶瑟儿~ 2021-01-06 23:37

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 st         


        
3条回答
  •  不思量自难忘°
    2021-01-07 00:38

    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.

    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 :)

    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.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题