| Author |
Constructors and Methods
|
ryan bohnert
Greenhorn
Joined: Feb 27, 2008
Posts: 15
|
|
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
Joined: Jul 08, 2003
Posts: 24061
|
|
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!
|
[Jess in Action][AskingGoodQuestions]
|
 |
Bill Shirley
Ranch Hand
Joined: Nov 08, 2007
Posts: 457
|
|
|
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)
|
Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
|
 |
 |
|
|
subject: Constructors and Methods
|
|
|