The order in which free blocks are executed in Java
- 2020-04-01 01:41:02
- OfStack
Here is an example:
The parent class
father.java
public class father {
static{//A static block
System.out.println("father'sSTATIC free block running");
}
{// non A static block
System.out.println("father'sfree block running");
}
public father(){
System.out.println("father'sconstructor running");
}
}
A subclass
son.java
public class son extends father{
static{//A static block
System.out.println("son'sSTATIC free block running");
}
{// non A static block
System.out.println("son's freeblock running");
}
public son() {
// TODO Auto-generated constructor stub
System.out.println("son'sconstructor running");
}
}
The class of the main function
test.java
public class test{
public static void main(String[] args) {
Class f;
try {
System.out.println("--------beforeload father--------");
f=Class.forName("freeblock.father");
System.out.println("--------afterload father---------");
System.out.println("--------beforeinitial father object--------");
f.newInstance();
System.out.println("--------afterinitial father object--------");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Class s;
try {
System.out.println("-------beforeload son--------");
s=Class.forName("freeblock.son");
System.out.println("--------afterload son-------");
System.out.println("--------beforeinitial son object----------");
s.newInstance();
System.out.println("--------afterinitial son object-----------");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Execution results:
-- -- -- -- -- -- -- -- before loadfather -- -- -- -- -- -- -- --
Father 's STATIC free blockrunning
-- -- -- -- -- -- -- -- after loadfather -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- before initial fatherobject -- -- -- -- -- -- -- --
Father 's free block running
Father 's constructor running
-- -- -- -- -- -- -- -- after initial fatherobject -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- before the load son -- -- -- -- -- -- -- --
Son's STATIC free block running
-- -- -- -- -- -- -- -- after the load son -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- before initial sonobject -- -- -- -- -- -- -- -- -- --
Father 's free block running
Father 's constructor running
Son 's free block running
Son 's constructor running
-- -- -- -- -- -- -- -- after initial son object -- -- -- -- -- -- -- -- -- -- -