• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overloaded Constructors - Share the Work.  RSS feed

Gregg Bolinger
Ranch Hand
Posts: 15304
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I am going back to the basics and trying to pick up some things that I missed when I started on JAVA and this is one of them.
Let's say I have a Class that I created and I have overloaded constructors, so for an example class let's say:

As you can see, 3 of the constructors will actually share some functionallity. All 3 will do the same thing with String name.
So my question is, do I just put the funcationllity for handling String name in all 3 methods or is there a more OO approach to doing this. And likewise for handling int x in the 2nd the 3rd constructor.
I know that I could create another method called someething like handleName(String name) and call that from each constructor, but that seems the same as just adding the functionallity into each constructor. Especially if the handleString only does something really simple.
[ June 06, 2003: Message edited by: Gregg Bolinger ]
Kathy Sierra
Cowgirl and Author
Posts: 1589
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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() {
Foo(int 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.
p.s. I haven't had enough coffee, so if I said anything really stupid here, I know someone will correct it
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!