File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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 | Flagged Topics | Hot Topics | Zero Replies
Register / Login
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: 629

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: 10535
    
    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: 40052
    
  28
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: 19068
    
  40


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: 19785
    
  20

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
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why to call static method from constructor ?