Initializing Fields

Common practice of initializing fields at the beginning of a class as following.

1 public class InitializingFieldsTest {
2   public static int age = 23;
3   public boolean flag = false;
4 }

Note:  It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice.

   It is only necessary that they be declared and initialized before they are used.

Static Initializing Blocks

1 static {
2    // code to initialize class variables
3 }

Note: A class can have any number of static initialization blocks, and they can appear anywhere in the class body.

Initializing Instance Members

  Normally, we initialize instance variables in a constructor. There are two alternatives to do this.

  Initializer blocks 

 1 public class InitializingFieldsTest {
 2   public int age;
 3   public boolean flag;
 4 
 5   // Initializer block for instance variables
 6   {
 7     age = 24;
 8     flag = true;
 9   }
10   // can omit the constructor
11 //  InitializingFieldsTest(){
12 //    age = 24;
13 //    flag = true;
14 //  }
15 
16   public static void main(String[] args) {
17     InitializingFieldsTest test = new InitializingFieldsTest();
18     System.out.println(test.age); // 24
19     System.out.println(test.flag); // true
20   }
21 }

  The Java compiler copies initializer blocks into every constructor.

  Therefore, this approach can be used to share a block of code between multiple constructors.

reference from: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

原文地址:https://www.cnblogs.com/yangwu-183/p/13491151.html