When Java instantiates an object, the class is loaded first, and the whole process of class loading is to introduce the class bytecode into memory, not the static variables in the class. The previous article has probably analyzed the class loading mechanism, the following is the instantiation process of the class.
First introduce the sample code
Parent class
Package Test;public class Fu {public int j = 9;public static int i = 10;static{i = 9; System.out.println ("Fu Static code block");} {j = 10; System.out.println ("Fu Constructs code block");} Public Fu () {System.out.println ("Fu_ construction Method");} public int Getj () {return J;} public void Setj (int j) {this.j = j;} public void A () {System.out.println ("a method of the parent class");}; public static void Staticmethod () {System.out.println ("Fu");}}
Sub-class
Package Test;import Com.sun.org.apache.xerces.internal.impl.xpath.regex.match;public class Zi extends Fu{public int j = 0;static {i = 3; System.out.println ("Zi Static code block");} public static int i = 2; {System.out.println ("Zi Construction Code block");} Public Zi () {System.out.println ("Zi constructor method"); public void A () {try {throw new Exception ()} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("A method of the subclass");} public int Getj () {return J;} public void Setj (int j) {this.j = j;}}
Execute the following code
The program prints the result as:
Fu Static code block
Zi Static code block
Fu Construction code block
Fu Construction method
Zi Constructing code blocks
Zi Construction method
We track it through the breakpoint debug to know that the specific operating process is:
The static variable assignment and static code blocks of the parent class are executed first (the order of execution is determined according to the program writing order )
Then execute the static variable assignment and static code block of the child class
The member variable assignment statement for the parent class is then executed ( at which time the member variable of the subclass is assigned the initial value of the Java program Zi object has two J variable initial values of 0)
Then execute the parent class's construction code block
To perform a parent class construction method
Execute a Subclass member assignment statement
Executing subclasses building blocks of code
To perform a subclass construction method
When we execute the following statement:
The result of the output is
The value of the J of the parent Class 9
The value of J for subclass 0
A method of subclasses
In particular:
When the subclass method overrides the parent class method, the subclass can only try-catch the statements that may have an exception if the parent class method does not declare an exception to be thrown