public class ParentClass
{
public ParentClass(int param);
}
public class MyClass extends ParentClass
{
private int _a;
private int _b;
private int _c;
public MyClass(String input)
{
_a=CalculateA(input);
_b=CalculateB(_a);
_c=CalculateC(_a);
super(_b+_c);
}
//a expensive procedure
private int CalculateA(String text);
private int CalculateB(int a);
private int CalculateC(int a);
}
Java doesn’t allow chained constructors to be anything other than the first method put in a constructor.
Chained constructors can’t call nonstatic methods as arguments (which removes the possibility of using Initialsers that return the value they initialize to).
How do I achieve the above code using legal Java?
Edit Indeed Java does not allow a constructor to do any calculations before the call to a parent’s class constructor, even if these involve only static methods (as your
calculateX‘s should be) and results only assigned to variables that are private to the class (like your_a,_band_c) or local to the constructor.There is a way around this, however: call another constructor with the result of the
calculateXcall assigned to its parameter – then you can access this result throughout the other constructor.Edit 2 With more calculations or more intermediate results to store for later use, this approach would lead to an even longer chain of constructors consisting only of
this(...)-calls. A more fancy solution with only two constructors, the public one and one private, is possible with a helper class (reasonably an inner class):(using the same private fields and static
calculateXmethods as above).