Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local chaining of constructors

 
Patrick Haley
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While studying for the SCJP Exam, I read about this technique, which appears to be quite nifty, but I'm wondering what practical purpose it would serve.

Has anyone locally chained constructors in applied code and, if so, to what end?

Thanks.
 
C Broussard
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say locally chain constructors, are you talking about overriding constructor signatures?


like

public class someobject{
int someobject_value = 0;
public someobject(){
someobject(1);
}
public someobject(int i){
someobject_value = i;
}
}


if this is what you're talking about then yes, this is perfectly
acceptable.

hope that helped.

www.binaryfrost.com
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right, although defining more than one constructor isn't "overriding",
it's just defining more than one constructor, and the syntax is:
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Has anyone locally chained constructors in applied code and, if so, to what end?


Often times you may want several constructors for convenience. By chaining them you can keep the bulk of the code in one constructor.
 
Brian Cole
Author
Ranch Hand
Posts: 908
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Patrick Haley:
Has anyone locally chained constructors in applied code and, if so, to what end?


Here's some real-world code I wrote the other day.
See if the chaining makes sense to you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic