• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors and Methods

 
ryan bohnert
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • 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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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!
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • 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)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic