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 setter calls 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 setter calls" Watch "Constructors and setter calls" New topic

Constructors and setter calls

John Dell'Oso
Ranch Hand

Joined: Apr 08, 2004
Posts: 130
Hi there,

Just a quick concept question. Are there any opinions out there with regards to constuctors calling its own class setter methods to initialise its instance fields?

I've recently used this technique a couple of times and I have had no issues with it. It works quite well as I can keep all my validation code in the setters and call the setters from the constructors as required.

Any thoughts on whether this is a good or bad approach would be appreciated.

David O'Meara

Joined: Mar 06, 2001
Posts: 13459

"Wayne Carey",
as a fellow Australian, I suspect your display name is fictitious. Unfortunately the JavaRanch display name rules do not allow fictitious names. Can you please edit your profile and select a valid name.

Accounts with invalid diaplay names get deleted, often without warning

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Constructor calling set methods (and other methods) should be fine. Be careful that constructor code does not pass "this" to any other object that might try to use it. "this" is not necessarily valid for use yet during the constructor.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Typically, I design my classes to be immutable. In otherwords, I avoid setter methods as often as possible. This is more of a design decision that an implementation issue. If you decide to use setters, I think you have a good idea with calling them from your constructor.


Java API Documentation
The Java Tutorial
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
From the constructor, if you are going to invoke an instance method of the object being constructed, may it be a private method. If it is not a private method, may it be a final method.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Constructors and setter calls
It's not a secret anymore!