aspose file tools*
The moose likes Beginning Java and the fly likes Static Initializers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static Initializers" Watch "Static Initializers" New topic
Author

Static Initializers

Chris C.
Greenhorn

Joined: Oct 08, 2004
Posts: 1
When a subclass is instantiated, will it's parent class' static initializer run?

I simply test printing to System.out seems like the answer is no, but I'm not sure why.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Static initializer code in the Parent class will execute once when the Child class is loaded (because this will also load the Parent class) -- whether or not an instance of either class is created.

Classes are loaded automatically by the JVM either when the first object of that class is created or the first time a static member of that class is accessed -- even if no object is created. (Alternatively, a class can be loaded "manually" using Class.forName(String).)

Non-static initializer code executes with each instantiation.


[ October 08, 2004: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
If the parent class was already loaded for one of the reasons mentioned, its static initializers won't run again when the child class is loaded. This may account for what you observed.


Mike Gershman
SCJP 1.4, SCWCD in process
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Mike Gershman:
If the parent class was already loaded for one of the reasons mentioned, its static initializers won't run again when the child class is loaded...

Yes, that's a good point. I should have been more clear in my first paragraph. Static initializers run only once, at class load time. And if the Parent class is not already loaded, then loading the Child class will also load the Parent class.
[ October 08, 2004: Message edited by: marc weber ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Initializers