• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Constructors and Methods

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is it a good programming practice to call a method from within a constructor.

Or should you create the object first... Then come back and call the method on the object.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Calling a final or private method from a constructor is always fine, and yes, it's good style if it reduces duplication or makes the code more readable.

Calling a non-final/non-private method -- specifically, calling a method that might be overridden -- is something you should do carefully. That's because when a parent class is being constructed, it will call the child's overridden version of the method. Sometimes that's exactly what you want -- it's a way for the child to customize the construction of the object. Other times, it's a bug waiting to happen, or even a security hole -- so be careful!
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would add that it's generally okay if you are calling the methods to initialize the object. But if you are performing work that the object will typically perform throughout its life cycle and many times, it is poor practice to call the method from the constructor. (IMHO)
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic