Creating multiple constructors isn't so bad. Just make the one with "all the parameters" do all the work, and the simpler ones supply default values.
Code:class Doer {
int x; // Default 0
int y; // Default 0
boolean doIt; // Default FALSE (but overridden in constructor(s))
// Constructors
Doer (int x, int y) {
this(x, y, true);
}
Doer (int x, int y, boolean doIt) {
this.x = x;
this.y = y;
this.doIt = doIt;
}
}
You can even have a (private, if desired) helper method that holds all the common code.
Code:class Doer {
int x; // Default 0
int y; // Default 0
boolean doIt; // Default FALSE (but overridden in constructor(s))
// Constructors
Doer (int x, int y) {
_init(x, y, true);
}
Doer (int x, int y, boolean doIt) {
_init(x, y, doIt);
}
// Helper method
private void _init (int x, int y, boolean doIt) {
this.x = x;
this.y = y;
this.doIt = doIt;
// and maybe some other tricky stuff here like opening
// system resources, doing calculations, etc
}
}
Indeed, having some sort of separate "init" function can be really handy for resetting/reusing an object later constructors can only be called at construction time, an init method can be called any time. Depending on what the init function does, maybe it is okay for it to be public (so callable from outside the class).
Code:Doer doer = new Doer(22, 33);
// ...
if (someSpecialCondition) doer.init(mouseX, mouseY, true);
-spxl