Three cases: Interpreting static code blocks and constructing code blocks.
I. Summary of static and non-static code blocks
1. Static code block:
Static code blocks are called first when a class is loaded (memory) and executed once. Static code blocks are often used to initialize class attributes. RunClassWill be called before loading.
2. Non-static code block:
A non-static code block is called first when a class object is created and loaded (in memory). Each time an object is created, that is, each object is loaded, the non-static code block is executed once. RunClass ObjectWill be called before loading.
3. Static methods and non-static methods: they are executed only when called. Static Methods belong to Classes. After loading a class, you can call static methods. Non-static methods belong to objects. After loading an object, you can call non-static methods.
Ii. Example
1 public class Cc {2 public static void main (String [] args) {3 test p = new test (); 4} 5} 6 7 class test {8 test () {// start execution when the class object is created. Creation is an execution. 9 System. out. println ("this is the constructor"); 10} 11 12 {// construct a code block, which is executed every time a class object is created before the constructor. 13 System. out. println ("this is the Construction Code block"); 14} 15 16 static {// static code block, the earliest execution, and the value is executed once. 17 System. out. println ("this is a static code block"); 18} 19}
Print result:
Demonstrate what will happen when called twice. Enhance your understanding of static code blocks.
1 public class Ccc {2 public static void main (String [] args) 3 {4 MyTest p = new MyTest (); 5 MyTest p2 = new MyTest (); // two calls 6} 7} 8 class MyTest {9 10 MyTest () {11 System. out. println ("this is the constructor"); 12} 13 14 {15 System. out. println ("this is the Construction Code block"); 16} 17 18 static {19 System. out. println ("this is a static code block"); 20 21} 22}
The output is as follows:
An example with parameters is introduced:
1 class Cccc {2 public static void main (String [] args) {3 new Person (77); 4 new Person (); 5} 6} 7 8 class Person {9 10 Person () {11 System. out. println ("a"); 12} 13 14 15 Person (int x) {// pay attention to the parameter !! 16 System. out. println (x); 17} 18 19 static {20 System. out. println ("B"); 21} 22 23 {24 System. out. println ("c"); 25} 26}
Print result: