这篇文章主要介绍了Java静态和非静态成员变量初始化过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
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
Afte