Foreword
Today, when watching Android ContentProvider implementation, I suddenly thought of the execution order of static domains, static blocks, non -static blocks, non -static blocks, and constructive functions during the new process of the Java class. In fact, this is a very classic issue, which is very examined to grasp the basic knowledge of Java. I believe there are also such problems during the interview process, and take advantage of the time to review it on the weekend.
in conclusion
Here is the sorting conclusion to everyone, and then I write a program to verify our conclusions. During the Java class being NEW, the execution order is as follows:
In the process of implementing the inheritance class, the initialization execution order is as follows:
Here you need to introduce static code blocks and non -static code blocks.
1. Static code block:
static {
}
2. Non -static code block
{{
}
The similarities and differences between static code blocks and non -static code blocks are as follows:
The best verification of the verification of the conclusion is to write the code to prove the results. First, let's take a look at the order of execution when the inheritance class initializes. The code is as follows:
Public Class Initodertest {Public Static Stration Static_field = "Static Properties"; // Static block static {System.out.println (Static_field); System.out.println ("Static State Code Block ");} Public String Field =" Non -Static Properties "; // Non -static blocks {system.out.println (field); system.out.println (" non -static code block ");} public initodertest () {system.out.println );} Public Static void main (string [] args) {initodrtest test = new initodertest ();}} Execution results:
Next, let's verify that when the Java class is inherited, the execution order is in line with our conclusions. The test code is as follows:
Class Parenttest {Public Static String Parent_Static_field = "Parent-Static Properties"; // Parent-Static block static {System.out.println (Parent_Static_field); System.out. Println ("Family-Static Code Block"); } PUBLIC Static String ParentField = "Family Class-Non-Static Attributes"; // Family-Non-Static Block {System.out.println (Parentfield); System.out.println ("Family-Non-Static Code Block"); } PUBLIC PAREATTTEST () {System.out.println ("Family -PuBlic Class Initodertest EXTENDS PAREATTTEST {Public Stration Static_field =" Static attribute "; // Static block static {system.out .println (static_field); System.out.println ("Static code block");} Public String Field = "Non -Static Properties"; // Non -Static Block {System.out.println (Field); System.out.pr. intln ("Non -Static Code Block");} Public Initodertest () {System.out.println ("Portomless Constructor"); Test ();} }The execution results are as follows: