Referring to “this” while invoking super constructor?

后端 未结 1 390
借酒劲吻你
借酒劲吻你 2021-01-17 11:19

I have a class A and write a subclass B. A has only one constructor which is parameterised. B has to call this super constructor of A. Now I want to use an Object as a param

相关标签:
1条回答
  • 2021-01-17 12:01

    The compiler is really preventing you from shooting yourself in the foot here. B isn't fully constructed until after the call to the super constructor, so if you pass this (if the compiler allowed it) as a reference, and it calls a method on B, B would be in an invalid state and cause all kinds of nasty problems (in fact, A is still not initialized, nor any class up the chain, including Object).

    The obvious solution is to provide the functionality outside of B and pass that to the constructor of the parameter. Specific solutions will depend on the specific problem, but a static nested class inside B (it needs to be static for the same reason - an inner class has an implicit reference to the outer class instance) could provide that functionality, perhaps. Maybe you need to rethink the relationship between the parameter, B and its super class. It all depends on the case.

    0 讨论(0)
提交回复
热议问题