Referring to "this" while invoking super constructor?
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 parameter. This object should call a method of B. So the parameter-object has to hold a reference of B or has to be an inner class.
public B(){
super.(new parameter(this))
}
Now when I want to invoke the constructor like... Eclipse says:
Cannot refer to 'this' nor 'super' while explicitly invoking a constructor
The only thing I see to get around this, is a set-method, to inject the "this"-instance into the parameter object. I would not like to edit the super-class.
Do you see any better w开发者_如何学运维ay around this.
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.
精彩评论