Java 初始化字段方式和顺序
Java 初始化字段方式和顺序:
-
类加载时直接初始化静态字段;
-
类加载时调用静态方法初始化静态字段;
-
实例化对象时,在调用构造函数之前代码块中初始化字段;
-
实例化对象时,在调用构造函数之时初始化字段;
初始化字段顺序1->2->3->4
代码如下:
public class Employee { //实例化对象时,在调用构造函数之前前初始化字段; private int id; // 实例化对象时初始化为0 private String name; // 实例化对象时初始化为null private boolean flag; // 实例化对象时初始化为false private static int age = 22; // 加载类时初始化为22 // 在构造函数之前初始化 { int num = 1111; // 实例化对象时初始化为1111 String name = "QA";// 实例化对象时初始化为QA setId(num); // 实例化对象时调用 SetName(name); // 实例化对象时调用 System.out.println("call instance method"); } //类加载时调用静态方法初始化静态字段; static { System.out.println("age is: " + age); age = 30; // 加载类时初始化为33 print(); // 加载类时时调用 } public void SetName(String name) { this.name = name; } public int getId() { return id; } public String getName() { return name; } public static int getAge() { return age; } public void setId(int num) { id = num; } public static void print() { System.out.println("call static method"); } public Employee() { // TODO Auto-generated constructor stub } public Employee(int id, String name) { // TODO Auto-generated constructor stub this.id = id; this.name = name; System.out.println("call constructor method"); } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("---------------------------"); System.out.println("age is: " + Employee.getAge()); System.out.println("---------------------------"); Employee e = new Employee(); System.out.println("id is: " + e.getId()); System.out.println("name is: " + e.getName()); System.out.println("---------------------------"); Employee e2 = new Employee(2222, "Dev"); System.out.println("id is: " + e2.getId()); System.out.println("name is: " + e2.getName()); } }
运行结果:
age is: 22
call static method
---------------------------
age is: 30
---------------------------
call instance method
id is: 1111
name is: QA
---------------------------
call instance method
call constructor method
id is: 2222
name is: Dev