• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling methods in constructors  RSS feed

 
Day Vide
Greenhorn
Posts: 8
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings,

Is it ok to call methods in class constructors ?

Everytime I try calling one I get this warning 'overridable method call in constructor'.

If not, what would be the good way to do this ?

Thank you
 
Paul Clapham
Sheriff
Posts: 22819
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's "ok" in the sense that it's legal in Java to do that. But if you call an overridable method from the constructor, and then write a subclass which actually overrides that method, then you're likely to run into confusing errors at run time because things aren't initialized in the order that you might expect.

As you may have already found out, if you declare that method to be final then you won't get that warning any more. That's because then that method can't be overridden and you're not going to have those confusing errors.

I know, it looks perfectly reasonable to have your constructor call a method called initializeComponent() which does all of the hard work of initializing a component, and to allow that method to be overridden by subclasses so that they can specify how they should be initialized. (That's what I did.) But it doesn't work, because of Java's order of initialization.

I would give you an example but my brain was so scarred by having to debug this issue and then fix it, I can't remember the details.

So start by declaring the method called from your constructor as final. If you find you need to override it in a subclass, then come back and we can talk about that.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!