wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Constructors and Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Constructors and Methods" Watch "Constructors and Methods" New topic
Author

Constructors and Methods

ryan bohnert
Greenhorn

Joined: Feb 27, 2008
Posts: 19
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: 24183
    
  34

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);
 
Consider Paul's rocket mass heater.
 
subject: Constructors and Methods
 
Similar Threads
refrence variable of object
Executor
Explicitly invoking finalize()
Recognising Folders
Using GregorianCalendaer class