Java class Loading process: (Take A.class as an example)
1. Locate the A.class class and call Findloaderclass (string) to determine if the class already exists
2. Execute the static member variable and the static method block in the parent class first
3. Execute the static member variable and the static method block in the subclass
4. Then execute the non-static member variable of the parent class, the static method block, and the constructor
5. Final execution subclass non-static member variables, static method blocks, and constructors
Note: The constructor is executed last.
The following is a description of the test code input:
(1) When there are no member variables in the class
1 Public classTest1 {2 Static{3SYSTEM.OUT.PRINTLN (5);4 }5 6 PublicTest1 () {7SYSTEM.OUT.PRINTLN (6);8 }9 {TenSYSTEM.OUT.PRINTLN (7); One } A } - - Public classTestextendsTest1 { the Static{ -SYSTEM.OUT.PRINTLN (1); - } - { +SYSTEM.OUT.PRINTLN (2); - } + PublicTest () { ASYSTEM.OUT.PRINTLN (3); at } - { -SYSTEM.OUT.PRINTLN (4); - } - Public Static voidMain (string[] args) { -Test test=NewTest (); in } -}
Output: 5 1 7 6 2 4 3
(2) When there are other instances of the object
1 Public classTest1 {2 StaticTest2 test22=NewTest2 ("Static_father_test2");3Test2 test2=NewTest2 ("Father_test2"); 4 Static{5SYSTEM.OUT.PRINTLN (5);6 }7 8 PublicTest1 () {9SYSTEM.OUT.PRINTLN (6);Ten } One { ASYSTEM.OUT.PRINTLN (7); - } - } the - Public classTest2 { - PublicTest2 (String str) { -System.out.println ("Test2:" +str); + } - } + Public classTestextendsTest1 { A StaticTest2 test22=NewTest2 ("static_test22"); atTest2 test2=NewTest2 ("Test2"); - Static{ -SYSTEM.OUT.PRINTLN (1); - } - { -SYSTEM.OUT.PRINTLN (2); in } - to PublicTest () { +SYSTEM.OUT.PRINTLN (3); - } the { *SYSTEM.OUT.PRINTLN (4); $ } Panax Notoginseng Public Static voidMain (string[] args) { -Test test=NewTest (); the } +}
Output printing:
Test2:static_father_test2
5
test2:static_test22
1
Test2:father_test2
7
6
Test2:test2
2
4
3
Sword refers to Offer-java class loading process