Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

confusion with constructor

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks:)
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

rizwana mujawar wrote:Thanks:)



You're welcome!
 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As a side note: this pattern is known as telescoping constructor(refer effective java-joshua bloch)
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic