Copy the code code as follows:
public class Test4 {
@Test
public void test(){
child child = new child();
}
}
class parent{
public static String parentStaticField = "Parent class static variable";
public String parentNormalField = "Parent class normal variable";
static {
System.out.println(parentStaticField);
System.out.println("Parent class static block");
}
{
System.out.println(parentNormalField);
System.out.println("Parent class ordinary block");
}
public parent(){
System.out.println("Parent class constructor");
}
}
class child extends parent{
public static String childStaticField = "Subclass static variable";
public String childNormalField = "Subclass normal variable";
static {
System.out.println(childStaticField);
System.out.println("Subclass static block");
}
{
System.out.println(childNormalField);
System.out.println("Subclass ordinary block");
}
public child(){
System.out.println("Subclass constructor");
}
}
Output:
Copy the code code as follows:
parent class static variable
parent class static block
Subclass static variables
subclass static block
Parent class ordinary variable
Parent class normal block
Parent class constructor
Subclass ordinary variables
Subclass normal block
Subclass constructor
Execution process:
1. When executing new child, the loader looks for the code of the compiled child class (that is, the child.class file). During the loading process, the loader notices that it has a base class, so it loads the base class again. This process will always happen whether you create a base class object or not. If the base class has another base class, then the second base class will also be loaded, and so on.
2. Perform static initialization of the root base class, then static initialization of the next derived class, and so on. This order is very important, because the "static initialization" of the derived class may depend on the correct initialization of the base class members.
3. When all necessary classes have been loaded, create a child class object.
4. If the child class has a parent class, then the constructor of the parent class is called. You can use super to specify which constructor to call.
The construction process and construction sequence of the base class are the same as those of the derived class. First, each variable in the base class is initialized in literal order, and then the rest of the constructor of the base class is executed.
5. Initialize the subclass member data in the order in which they are declared, and execute the rest of the subclass constructor.