File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Constructors and Methods

ryan bohnert

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

Joined: Jul 08, 2003
Posts: 24199

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 -
if (Posts < 30) JavaRanchFAQ);
I agree. Here's the link:
subject: Constructors and Methods
jQuery in Action, 3rd edition