• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Unexpected ouput according to order of initialization

 
Ranch Hand
Posts: 86
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
On page 203 in the book 'Certified Associate Java SE 8 Programmer I' by Jeanne Boyarsky and Scott Selikoff, there is a code sample that is supposed to give output based on the order of initialization:

To my understanding, the order of initialization is:
1. superclass
2. static variables
3. instance variables
4. the constructor

However, the output from the code above is:
1
I'm the statement before creating a new InitializationOrder object.
Torchie
constructor

Why does the print statement for the static variable on line 11 print before the output statement on line 17? The initialization wasn't invoked until line 18.
In other words, why wasn't the output:
I'm the statement before creating a new InitializationOrder object.
1
Torchie
constructor
 
Sheriff
Posts: 27468
88
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sam Peterson wrote:The initialization wasn't invoked until line 18.



Not so. Your class is named InitializationOrder and so the class is loaded before its static main(String...) method can be run. And as part of loading the class, its static initializers are run before anything else happens. The block including line 11 is a static initializer.

What happens at line 18 is that an instance of the class InitializationOrder is created (via a constructor). At that point the constructor and the instance initializers are run, in some order which this example is supposed to be teaching you.
 
Marshal
Posts: 76888
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This appears to be a similar question to what you asked here.
 
Where does a nanny get ground to air missles? Protect this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic