Static code block, construction code block, construction method execution sequence, static Construction
Construct code blocks, static code blocks, and constructor methods are three different code blocks. What are the differences between them?
Introduction to one or three code blocks
1 class A 2 {3 // construct code block 4 {5 System. out. println ("construct code block A"); 6} 7 // static code block 8 static 9 {10 System. out. println ("static code block A"); 11} 12 // constructor 13 public A () 14 {15 System. out. println ("constructor A"); 16} 17}
Ii. execution sequence of the three elements
In order to clarify the execution sequence of the three, Class A is instantiated and tested for A single instance and multiple instances respectively.
2.1 Single Instance
1 class Demo2 {3 public static void main(String[] args)4 {5 new A();6 }7 }
1 class Demo2 {3 public static void main (String [] args) 4 {5 new A (); 6 new A (); 7 new A (); 8} 9}
1 class B extends A 2 {3 // construct code block 4 {5 System. out. println ("construct code block B"); 6} 7 // static code block 8 static 9 {10 System. out. println ("static code block B"); 11} 12 // constructor 13 public B () 14 {15 System. out. println ("constructor B"); 16} 17} 18 19 class Demo20 {21 public static void main (String [] args) 22 {23 new B (); 24} 25}
Iv. Summary
1. When creating an object, the execution sequence of the three elements is: static code block --> construction method;
2. Each time an object is created, the Construction Code block and construction method are executed once. No matter how many objects are created, the static code block is only executed once when the first object is created;
3. When a subclass object is created, the static code block of the subclass is executed after the static code block of the parent class, but takes precedence over the Construction Code block and construction method of the parent class;
4. When a subclass object is created, the constructor block of the subclass is executed after the constructor of the parent class.
Author: xin, published in blog
Reprinted please indicate the source, welcome to mail exchange: zhuanxinxin@foxmail.com