• Post Reply Bookmark Topic Watch Topic
  • New Topic

confusion with constructor  RSS feed

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



They are saying.."The benefits of having overloaded constructor is that it offers flexible ways to create objects from your class.The benefits of having one constructor invoke another overloaded constructor is to avoid code duplication. (Iam not getting from here onward..). In Jaanwar example there wasnt any code other than setting name,but imagine after line 4 there was still more work to be done in the constructor. By putting all the other constructor work in just one constructor, and then having the other constructor invoke it,you dont have to write and maintain multiple versions of that other important constructor code.Basically each of the other not the real one overloaded constructor will call another overloaded constructor,passing it whatever data it needs."
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose it looked like this:



If the second constructor didn't invoke the first one, then we would have to repeat lines // new line 1 and // new line 2 in the second constructor. Having it invoke the first constructor eliminates that code duplication.
 
rizwana mujawar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rizwana mujawar wrote:Thanks


You're welcome!
 
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a side note: this pattern is known as telescoping constructor(refer effective java-joshua bloch)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!