GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Calling methods from Constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Calling methods from Constructors" Watch "Calling methods from Constructors" New topic
Author

Calling methods from Constructors

Joel Cochran
Ranch Hand

Joined: Mar 23, 2001
Posts: 301
Is it OK to call a classes methods from one of its constructors? I can't think why it wouldn't be but would like some guidance.
I have a class with several instance variables. Some of the variables get populated through a JDBC call to a Database, but I don't want to muck up my constructor code with a lot of this stuff. I also don't want the object to exist without these variables from the database populated, so I thought I'd put the JDBC pieces into a method and let the constructor call that method.
Is this normal? It seems to me that none of the examples I have seen do this...
Thanks


Wait a minute, I'm trying to think of something clever to say...<p>Joel
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Yes, it's "Ok". Very normal. I do it all the time, for the exact reason you mentioned, to keep your code tidy.
The ONE caveat to remember is that you must be very careful calling polymorphic methods from a constructor, because until the constructor completes running, the object you are creating is not fully instantiated.
For example,

Oher than this little gotcha, it's a fine to call other methods.
Rob

[ January 15, 2002: Message edited by: Rob Ross ]

Rob
SCJP 1.4
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Hello,
A note for beginners like me who like it spelled out:
In the constructor, you obviously cannot reference properties of the object you are creating until the object's properties have been created. Duh!
[ January 15, 2002: Message edited by: Dirk Schreckmann ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1747
    
    2
Originally posted by Rob Ross:
The ONE caveat to remember is that you must be very careful calling polymorphic methods from a constructor, because until the constructor completes running, the object you are creating is not fully instantiated.

I've even seen the recommendation that if you're going to call a class's own instance methods from within its constructor, those methods should be private/final.
[ January 15, 2002: Message edited by: Michael Matola ]
Joel Cochran
Ranch Hand

Joined: Mar 23, 2001
Posts: 301
Thanks everyone!
 
GeeCON Prague 2014
 
subject: Calling methods from Constructors