This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
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 Head First Android this week in the Android 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
Author

why to call static method from constructor ?

chetan dhumane
Ranch Hand

Joined: Jan 07, 2009
Posts: 636

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


Author @ http://www.ideasforideas.org/
Moody blogger who do not like to behave like target setting machines work.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10733
    
    9

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
Sheriff

Joined: Oct 13, 2005
Posts: 43335
    
  32
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: 19925
    
  43


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: 20046
    
  30

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 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: why to call static method from constructor ?
 
It's not a secret anymore!