1. Basic Concepts
1. Construct a code block to initialize all objects.
2. Constructor, which only initializes the corresponding object.
3. Local code blocks, which control the life cycle of local variables.
2. Example code
1 class Person 2 { 3 private int age; 4 // Construct the code block. Initialize all objects. 5 { 6 System.out.println("Construction code block..." ); 7 } 8 9 // The constructor only initializes the corresponding object. 10 Person () 11 { 12 System.out.println("person..." ); 13 } 14 Person ( int age) 15 { 16 this .age = age; 17 System.out.println("person(age)..." ); 18 } 19 // General function. Executed when called. 20 public void code() 21 { 22 int x = 8 ; 23 System.out.println("x="+ x); 24 } 25 } 26 class CodeDemo 27 { 28 public static void main(String[] args) 29 { 30 Person p1 = new Person(); 31 Person p2 = newPerson(4 ); 32 33 // Local code block, which controls the life cycle of local variables. 34 { 35 int x = 5 ; 36 System.out.println("x="+ x); 37 } 38 p1.code(); 39 } 40 }
3. Code running