Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why to call static method from constructor ?

 
chetan dhumane
Ranch Hand
Posts: 641
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
Saloon Keeper
Posts: 11092
13
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
Sheriff
Pie
Posts: 49733
69
  • 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
Marshal
Pie
Posts: 21385
84
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
Pie
Posts: 20606
60
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic