Java中非静态成员变量、静态成员变量的初始化时机。
非静态变量
我们在这里分析三种结构,着重分析这三种结构的初始化顺序:
- 成员变量初始化语句;
- 成员变量初始化块;
- 构造函数;
示例一:
public class MyTest {
private String name = "wei.hu";
public MyTest(String name) {
System.out.println("This is constructor. Will assign the variable name to: " + name + ".");
System.out.println("Before the name was modified: " + this.name);
this.name = name;
System.out.println("After the name was modified: " + this.name);
}
{
System.out.println("This is initialize block. Will assign the variable name to: chouchou");
System.out.println("Before the name was modified: " + this.name);
this.name = "chouchou";
System.out.println("After the name was modified: " + this.name);
}
public String getName() {
return name;
}
public static void main(String[] args) {
MyTest myTest = new MyTest("mengna");
System.out.println(myTest.getName());
}
}
#输出
This is initialize block. Will assign the variable name to: chouchou
Before the name was modified: wei.hu
After the name was modified: chouchou
This is constructor. Will assign the variable name to: mengna.
Before the name was modified: chouchou
After the name was modified: mengna
mengna
分析:
1. 先执行了初始化语句;
2.