For a long time not to see this content, write an article Let yourself remember, by the way share.
First, write the code to test the results.
Test code:
Public class Test { publicstaticvoid main (string[] args) { new Test2 (); }}
View Code
Sub-class Code:
Public classTest2extendstest3{{System.out.println ("Subclass code Block"); } PrivateString address =getaddress (); Static{System.out.println ("Subclass Static code block"); } Private StaticString name =Get1name (); PublicTest2 () {System.out.println ("Subclass Constructor Method"); } PrivateString getaddress () {System.out.println ("Child class member variable"); return NULL; } Private StaticString Get1name () {System.out.println ("Sub-class static variable"); return NULL; }}
View Code
Parent Class Code:
Public classTest3 {Private StaticString name =GetName (); PrivateString address =getaddress (); Static{System.out.println ("Parent class static code block"); } {System.out.println ("Parent Class code block"); } PublicTest3 () {System.out.println ("Parent class constructor"); } PrivateString getaddress () {System.out.println ("Parent class member variable"); return NULL; } Private StaticString GetName () {System.out.println ("Parent class static variable"); return NULL; }}
View Code
The above code can verify the order of class loading.
To run the code, the console prints the following results:
There is a case of the parent class. png
Case with no parent class. png
Changing the order of the Code multiple times, it is found that the loading order of variables and code blocks is related to the order of the Code.
To summarize:
In the absence of a parent class, the load order is:
Static member variables, static code blocks---member variables, code block----construction methods.
In the case of a parent class, the load order is:
Parent class static member variable, parent class static code block---Subclass static member variable, subclass static code block-----Parent class member variable, parent class block of code
----The construction method of the parent class-----The subclass member variable, subclass code block----Sub-class construction method.
Java Class load Order