• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling methods from Constructors

 
Joel Cochran
Ranch Hand
Posts: 301
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1826
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 301
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic