• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Seeking Clarification on Class Initialisation and Execution Order in Java

 
Greenhorn
Posts: 16
1
  • Number of slices to send:
    Optional 'thank-you' note:
Hello,

I am currently studying for the OCP Java 17 exam, and I answered the following question incorrectly:


Question: What is printed by the following program?

A: 182640
B: 182943
C: 182493
D: 421389
E: The code does not compile.
F: The output cannot be determined until runtime.



The right answer to this question is 182493. Which I think it was a fairly easy question.

However, it's clear I do not fully understand how the compiler sets the order of initialization.

Could anyone please point me to specific sections or topics in Java textbooks or official documentation that detail these concepts? I'm looking for resources that could help clarify the rules and execution order for class and object initialization, especially in the context of inheritance.

Thank you in advance for your guidance and assistance!
 
Master Rancher
Posts: 4905
74
  • 2
  • Number of slices to send:
    Optional 'thank-you' note:
The legalistic, nitpicky,  but authoritative answer is given by JLS 12.4: Initialization of classes and Interfaces, and JLS 12.5 Creation of New Class Instances.  Specifically this section:

JLS 12.4 wrote:
7. Next, if C is a class rather than an interface, then let SC be its superclass and let SI1, ..., SIn be all superinterfaces of C that declare at least one default method. The order of superinterfaces is given by a recursive enumeration over the superinterface hierarchy of each interface directly implemented by C (in the left-to-right order of C's implements clause). For each interface I directly implemented by C, the enumeration recurs on I's superinterfaces (in the left-to-right order of I's extends clause) before returning I.

For each S in the list [ SC, SI1, ..., SIn ], if S has not yet been initialized, then recursively perform this entire procedure for S. If necessary, verify and prepare S first.

If the initialization of S completes abruptly because of a thrown exception, then acquire LC, label the Class object for C as erroneous, notify all waiting threads, release LC, and complete abruptly, throwing the same exception that resulted from initializing S.

8. Next, determine whether assertions are enabled (§14.10) for C by querying its defining class loader.

9. Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.


Item 7 boils down to initialize the superclass before any subclass.  Item 9 justifies printing "1"", and then "8", in the code given.

And then later, this section:

JLS 12.5 wrote:3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.

4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.

5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.


Item 3 boils down to perform instance initialization for a superclass before instance initialization of any subclass.  For the superclass Antelope, item 4 then justifies printing "2", and item 5 justifies printing "4".  Then for subclass Gazelle, item 4 justifies printing "9", and item 5 justifies printing "3".

There are probably other sources floating around that present that info in a more digestible manner.  But the JLS would be the official specification - warts and all.

 
Mert Y. Ertugrul
Greenhorn
Posts: 16
1
  • Number of slices to send:
    Optional 'thank-you' note:
Thanks, Mike, this is exactly what I am looking for.

I also wrote this code to understand how it works, if anyone is interested



1. Initializing static variable in Superclass
2. Static block in Superclass
3. Initializing static variable in Subclass
4. Static block in Subclass
5. Main method starts
6. Initializing instance variable in Superclass
7. Instance initializer block in Superclass
8. Constructor in Superclass
9. Initializing instance variable in Subclass
10. Instance initializer block in Subclass
11. Constructor in Subclass
12. Main method ends

 
Ranch Hand
Posts: 55
1
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
Mert,
the numbering in your output might be a little bit misleading. The sequence of class variable initializers and static initialization blocks (or instance variable initializers and initialization blocks)  depends on their order in a class declaration.

Edit. From the JLS:

8.3.2. Field Initialization wrote:Note that static fields that are constant variables (§4.12.4) are initialized before other static fields (§12.4.2, step 6). This also applies in interfaces (§9.3.1). When such fields are referenced by simple name, they will never be observed to have their default initial values (§4.12.5).


4.12.4. final Variables wrote:A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.29). Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1), reachability (§14.22), and definite assignment (§16.1.1).

 
Mert Y. Ertugrul
Greenhorn
Posts: 16
1
  • Number of slices to send:
    Optional 'thank-you' note:
Good eye Ira, you are right, it is an important point.

I summarise the order like this:

  • 1. Static Variables and Static Blocks of Super-class (in the order they appear in the class).
  • 2. Static Variables and Static Blocks of Sub-class (in the order they appear in the class).
  • 3. Main Method is called (begins execution).
  • 4. Instance Variables and Instance Initializer Blocks of Super-class (in the order they appear in the class).
  • 5. Constructor of Super-class.
  • 6. Instance Variables and Instance Initialiser Blocks of Sub-class (in the order they appear in the class).
  • 7. Constructor of Sub-class.
  •  
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    reply
      Bookmark Topic Watch Topic
    • New Topic
    vceplus-200-125    | boson-200-125    | training-cissp    | actualtests-cissp    | techexams-cissp    | gratisexams-300-075    | pearsonitcertification-210-260    | examsboost-210-260    | examsforall-210-260    | dumps4free-210-260    | reddit-210-260    | cisexams-352-001    | itexamfox-352-001    | passguaranteed-352-001    | passeasily-352-001    | freeccnastudyguide-200-120    | gocertify-200-120    | passcerty-200-120    | certifyguide-70-980    | dumpscollection-70-980    | examcollection-70-534    | cbtnuggets-210-065    | examfiles-400-051    | passitdump-400-051    | pearsonitcertification-70-462    | anderseide-70-347    | thomas-70-533    | research-1V0-605    | topix-102-400    | certdepot-EX200    | pearsonit-640-916    | itproguru-70-533    | reddit-100-105    | channel9-70-346    | anderseide-70-346    | theiia-IIA-CIA-PART3    | certificationHP-hp0-s41    | pearsonitcertification-640-916    | anderMicrosoft-70-534    | cathMicrosoft-70-462    | examcollection-cca-500    | techexams-gcih    | mslearn-70-346    | measureup-70-486    | pass4sure-hp0-s41    | iiba-640-916    | itsecurity-sscp    | cbtnuggets-300-320    | blogged-70-486    | pass4sure-IIA-CIA-PART1    | cbtnuggets-100-101    | developerhandbook-70-486    | lpicisco-101    | mylearn-1V0-605    | tomsitpro-cism    | gnosis-101    | channel9Mic-70-534    | ipass-IIA-CIA-PART1    | forcerts-70-417    | tests-sy0-401    | ipasstheciaexam-IIA-CIA-PART3    | mostcisco-300-135    | buildazure-70-533    | cloudera-cca-500    | pdf4cert-2v0-621    | f5cisco-101    | gocertify-1z0-062    | quora-640-916    | micrcosoft-70-480    | brain2pass-70-417    | examcompass-sy0-401    | global-EX200    | iassc-ICGB    | vceplus-300-115    | quizlet-810-403    | cbtnuggets-70-697    | educationOracle-1Z0-434    | channel9-70-534    | officialcerts-400-051    | examsboost-IIA-CIA-PART1    | networktut-300-135    | teststarter-300-206    | pluralsight-70-486    | coding-70-486    | freeccna-100-101    | digitaltut-300-101    | iiba-CBAP    | virtuallymikebrown-640-916    | isaca-cism    | whizlabs-pmp    | techexams-70-980    | ciscopress-300-115    | techtarget-cism    | pearsonitcertification-300-070    | testking-2v0-621    | isacaNew-cism    | simplilearn-pmi-rmp    | simplilearn-pmp    | educationOracle-1z0-809    | education-1z0-809    | teachertube-1Z0-434    | villanovau-CBAP    | quora-300-206    | certifyguide-300-208    | cbtnuggets-100-105    | flydumps-70-417    | gratisexams-1V0-605    | ituonline-1z0-062    | techexams-cas-002    | simplilearn-70-534    | pluralsight-70-697    | theiia-IIA-CIA-PART1    | itexamtips-400-051    | pearsonitcertification-EX200    | pluralsight-70-480    | learn-hp0-s42    | giac-gpen    | mindhub-102-400    | coursesmsu-CBAP    | examsforall-2v0-621    | developerhandbook-70-487    | root-EX200    | coderanch-1z0-809    | getfreedumps-1z0-062    | comptia-cas-002    | quora-1z0-809    | boson-300-135    | killtest-2v0-621    | learncia-IIA-CIA-PART3    | computer-gcih    | universitycloudera-cca-500    | itexamrun-70-410    | certificationHPv2-hp0-s41    | certskills-100-105    | skipitnow-70-417    | gocertify-sy0-401    | prep4sure-70-417    | simplilearn-cisa    |
    http://www.pmsas.pr.gov.br/wp-content/    | http://www.pmsas.pr.gov.br/wp-content/    |