Howdy
Just Say This()
No need to duplicate code in each constructor -- you can use the magic keyword this() to invoke your own overloaded constructors. So you make ONE that is "the real one" and the others simply invoke it using this():
The only rules you must remember are:
*If you use *this* in a constructor (to invoke an overloaded constructor), it MUST be the very first statement in the constructor.
* You cannot mix both super() and this() together in the same constructor (each requires that it be the first thing in the constructor).
* Any constructor that invokes an overloaded constructor will NOT start the superconstructor chaining process. Superconstructor chaining happens only in constructors that do not say this().
If you something that looks like this:
Foo() {
this(42);
}
Foo(int i) {
super(i);
}
* The order of invocation looks like this:
1) a constructor is invoked
2) instance variables are given default values for their type (which means they do NOT get the values they have been explicitly initialized with.
3) the constructor invokes another overloaded constructor
4) the overloaded constructor invokes super()
(at this point, instance variables STILL do not have their explicitly assigned values!)
5) super constructor chaining happens
6) all super constructors are popped off the stack and we return back to the constructor that invoked super(i)
7) instance variables are given their initial values
8) the constructor completes, and is popped off the stack
9) the first constructor invoked (the constructor that calls this()) completes.
cheers,
-Kathy
p.s. I haven't had enough
coffee, so if I said anything really stupid here, I know someone will correct it