Saturday, February 20, 2010

Programmer - Is it possible to do computation before super() in the constructor?

Programmer Question

Given that I have a class Base that has a single argument constructor with a TextBox object as it's argument. If I have a class Simple of the following form:



public class Simple extends Base {
public Simple(){
TextBox t = new TextBox();
super(t);
//wouldn't it be nice if I could do things with t down here?
}
}


I will get a error telling me that the call to super must be the first call in a constructor. However, oddly enough, I can do this.



public class Simple extends Base {
public Simple(){
super(new TextBox());
}
}


Why is it that this is permited, but the first example is not? I can understand needing to setup the subclass first, and perhaps not allowing object variables to be instantiated before the super-constructor is called. But t is clearly a method (local) variable, so why not allow it?



Is there a way to get around this limitation? Is there a good and safe way to hold variables to things you might construct BEFORE calling super but AFTER you have entered the constructor? Or, more generically, allowing for computation to be done before super is actually called, but within the constructor?



Thank you.

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails