Hi, I am really enjoying going through this book but it seems they have some typos in dome of the excercises which is frustrating.
On page 310 they have this code in a "Be the Compiler". On page 312 they say the StaticSuper constructor just needs () in its signature, which is straightforward. However they don't mention any other changes needed for it to compile.
I am getting 2 errorsCannot define static initializer in inner type StaticSuper.StaticTestsStaticSuper.javaphilline 16November 1, 2005 12:14:24 PM422
SeverityDescriptionResourceIn FolderLocationCreation TimeId 2No enclosing instance of type StaticSuper is accessible. Must qualify the allocation with an enclosing instance of type StaticSuper (e.g. x.new A() where x is an instance of StaticSuper).StaticSuper.javaphilline 33November 1, 2005 12:14:24 PM424
Can you please give me an insight into what are the do's/don't with static in this case? When this happens at the end of chapters it has you questioning the principles you think you have understood from the rest of the chapter.
Ben Polaski wrote:Thanks for clearing that out.Can you explain where the StaticSuper intializer is called?
The static initializer is never explicitly called. It is executed when the class is initially loaded. It gets loaded basically the first time a reference to the class is made at run time. So in this example, the StaticTests class is loaded in order to call its main() method. Before the main() method can be called, the StaticTests class must be loaded and initialized. Because the StaticTests class has a super class, before it can be initialized, its super class must be loaded and initialized. So StaticTests initialization is put on hold and StaticSuper is loaded and initialized. Because StaticSuper also has a super class (Object), its initialization is put on hold until Object is done being loaded and initialized. Once Object is done being initialized, StaticSuper is initialized - and that means its static initializers are run (and its static variables are assigned values). When StaticSuper is done being initialized, StaticTests will be initialized and its static initializers will be run (and static variables assigned). All that gets done and then the main() method can get executed.
So it runs like this:
StaticTests.main() is called
-- StaticTests.class is loaded
---- StaticSuper.class is loaded
------ Object.class is loaded
------ Object.class is initialized
---- StaticSuper.class is initialized
-- StaticTests.class is initialized
StaticTests.main() is executed.