Java – Reference “this” when calling the super constructor?

I have a Class A and write a subclass B. only one constructor is parameterized B must call this super constructor of A

public B(){
   super.(new parameter(this))
}

Now, when I want to call the constructor like...: Eclipse says:

The only thing I see is to set the method and inject "this" into the parameter object I don't want to edit superclasses

Do you see a better way?

Solution

The compiler really prevents you from shooting yourself here Before calling the super constructor, B is not completely constructed, so if you pass this (if the compiler allows it) as a reference and it calls a method in B, B will be in an invalid state and cause all kinds of annoying problems (in fact, a has not been initialized, and there is no chain of classes, including object)

The obvious solution is to provide functions other than B and pass them to the constructor of parameters The specific solution will depend on the specific problem, but a static nested class inside B (which needs to be static for the same reason) – an internal class has an implicit reference to an external class instance) may provide this function Perhaps you need to reconsider the relationship between parameter B and its superclass It all depends on the situation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>