class A {
private List<Object> data = new ArrayList<Object>();
}
2)在构造函数中分配初始值:
class A {
private List<Object> data;
public A() {
data = new ArrayList<Object>();
}
}
这两者都假设您不希望将“ data”作为构造函数参数传递。
如果像上面那样将过载的构造函数和内部数据混合在一起,事情就有点棘手了:
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
data = new ArrayList<Object>();
name = "Default name";
userFriendlyName = "Default user friendly name";
}
public B(String name) {
data = new ArrayList<Object>();
this.name = name;
userFriendlyName = name;
}
public B(String name, String userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
EDIT: I've interpreted your question as "how do I initialise my instance variables", not "how do initialiser blocks work" as initialiser blocks are a relatively advanced concept, and from the tone of the question it seems you're asking about the simpler concept. I could be wrong.
This code should illustrate the use of them and in which order they are executed:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized)
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed 没错 before the code in constructor.
对象是多态创建的,但是在进入类 B 及其主方法之前,JVM 初始化所有类(静态)变量,然后通过静态初始化块(如果有的话) ,然后进入类 B 并开始执行主方法。它进入类 B 的构造函数,然后立即(隐式地)调用类 A 的构造函数,使用多态性类 A 构造函数体中调用的方法(重写方法)是在类 B 中定义的方法,在这种情况下,在重新初始化之前使用名为 instanceVariable 的变量。在关闭类 B 的构造函数之后,线程被返回到类 B 的构造函数,但是它首先进入非静态初始化块,然后打印“构造函数”。为了更好地理解使用某些 IDE 进行调试,我更喜欢使用 Eclipse。