File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes why to call static method from constructor ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why to call static method from constructor ?" Watch "why to call static method from constructor ?" New topic

why to call static method from constructor ?

chetan dhumane
Ranch Hand

Joined: Jan 07, 2009
Posts: 641

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.


Author @
Moody blogger who do not like to behave like target setting machines work.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10768

How much time does it take to write a few lines like these and try it out yourself?

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45293
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

Joined: Sep 28, 2004
Posts: 20370

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor

Joined: Oct 27, 2005
Posts: 20184

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.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: why to call static method from constructor ?
It's not a secret anymore!