• Post Reply Bookmark Topic Watch Topic
  • New Topic

why to call static method from constructor ?  RSS feed

 
chetan dhumane
Ranch Hand
Posts: 643
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all ,

if i have a class with constrctor , can i call a non-static method from constructor(method is declared within a class).
If not then what is the reason.

Thanks
Chetan
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How much time does it take to write a few lines like these and try it out yourself?

 
Campbell Ritchie
Marshal
Posts: 55785
164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your non-static method works from the constructor, make that method final or give it private access. It doesn't make much different in simple classes, but if the method is overridden and changed, you might introduce subtle errors.
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I actually don't recall why, or even know if this is true anymore... so take with a grain of salt...

I believe that you are not allowed to call an instance method, that returns a result, and use that result as a parameter to the super() call.

Henry
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, you can't put any non-static method in a call to "this(...)" or "super(...)", because at that time the object's parent class' constructor still has to run. Only after that has completed can you call non-static methods.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!