aspose file tools
The moose likes Beginning Java and the fly likes why to call static method from constructor ? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "why to call static method from constructor ?" Watch "why to call static method from constructor ?" New topic
Author

why to call static method from constructor ?

chetan dhumane
Ranch Hand

Joined: Jan 07, 2009
Posts: 628

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


http://www.androcid.com/
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 8439

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


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

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

Joined: Sep 28, 2004
Posts: 16695
    
  19


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


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

Joined: Oct 27, 2005
Posts: 19216

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.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: why to call static method from constructor ?
 
Similar Threads
can i call a consturctor from a static method?
Static & Class Variables
when static why does answer change?
Overloading wih static methods
about super key