I’m having some trouble using multiple constructors in java.
what I want to do is something like this:
public class MyClass {
// first constructor
public MyClass(arg1, arg2, arg3) {
// do some construction
}
// second constructor
public MyClass(arg1) {
// do some stuff to calculate arg2 and arg3
this(arg1, arg2, arg3);
}
}
but I can’t, since the second constructor cannot call another constructor, unless it is the first line.
What is the common solution for such situation?
I can’t calculate arg2 and arg3 “in line”. I thought maybe creating a construction helper method, that will do the actual construction, but I’m not sure that’s so “pretty”…
EDIT: Using a helper method is also problematic since some of my fields are final, and I can’t set them using a helper method.
Typically use another common method – a “construction helper” as you’ve suggested.
The alternative is a Factory-style approach in which you have a
MyClassFactorythat gives youMyClassinstances, andMyClasshas only the one constructor:I definitely prefer the first option.