tags:

views:

227

answers:

1

Hi,

I have a class A and write a subclass B. A has only one constructor which is parameterised. B has to call this super constructur 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 contructe 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 way around this.

+7  A: 

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.

Yishai
I know how to solve it. The real problem is, that the super class is "old" code. I'm reusing it in a little bit different context. I was searching for a elegant solution. But I think there is no. The is the price for reusing the old code.
You could just compose it out, placing the new class as a wrapper around the old one. Does the old class implement an interface that you can implement with your new object?
Joe
@c0d3x, you could post your solution (in a separate question) and ask if there is a more elegant solution. Seeing your solution would answer a lot of questions about the specific case involved.
Yishai