Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Initializers

 
Chris C.
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic