Java class loading sequence and java Loading Sequence
I haven't read this content for a long time. I will write an article to keep it in mind and share it with me by the way.
First, write the code to verify the result.
Test code:
public class Test { public static void main(String[] args) { new Test2(); }}
View Code
Subclass code:
Public class Test2 extends Test3 {System. out. println ("subclass code block");} private String address = getAddress (); static {System. out. println ("subclass static code block");} private static String name = get1Name (); public Test2 () {System. out. println ("subclass constructor");} private String getAddress () {System. out. println ("subclass member variable"); return null;} private static String get1Name () {System. out. println ("subclass static variable"); return null ;}}
View Code
Parent code:
Public class Test3 {private static String name = getName (); private String address = getAddress (); static {System. out. println ("parent static code block");} {System. out. println ("parent code block");} public Test3 () {System. out. println ("parent constructor");} private String getAddress () {System. out. println ("parent class member variable"); return null;} private static String getName () {System. out. println ("parent static variable"); return null ;}}
View Code
The above code can check the order of class loading.
Run the code. The console prints the result as follows:
With a parent category. PNG
No parent category. PNG
It is found that the loading sequence of variables and code blocks is related to the order in the code.
Summary:
If no parent class exists, the loading sequence is:
Static member variables, static code blocks --- member variables, code blocks ---- constructor.
When a parent class exists, the loading sequence is:
Static member variables of the parent class, static code blocks of the parent class --- static member variables of the Child class, static code blocks of the Child class ----- parent member variables and parent code blocks
---- Parent class constructor ----- Child class member variable, Child class code block ---- Child class constructor.