public class Test {
private int var1 = 1;
// These are the troublesome lines
public String[] name = new String[10];
// Use a constructor for initialization or
// declare the string array as public String[] name = {"Mary" };
public Test() {
name[0] = "Mary"; // When I remove this line, both the errors go away
}
public int var2 = 10;
}
在java中,您必须将语句放入方法/块中。
例如
public class TestB {
public String[] s = new String[10];
{
s[0] = "10";
}
}
实际上是合法的(但我不会使用它,除了静态成员)
编辑:关于静态成员的说明
通常我们必须使用纯静态对象,在这种情况下,提供初始化的一种简单方法是使用匿名静态块。就像是:
public class TestStatic {
private String [] someStaticStringArray = new String [10];
static {
someStaticStringArray[0] = "foo";
someStaticStringArray[1] = "bar";
}
// Or better with static HashMaps
private static HashMap<String, String> hm = new HashMap<String, String>();
static {
hm.put("key", "val");
hm.put("key2", "val2");
hm.put("key3", "val3");
}
}
对于静态数据成员,当我没有办法提供工厂方法或工厂对象时,我就使用这种方式。对于非静态数据成员,我更喜欢使用构造函数,即使匿名块也有效。
在 java 中提供初始化的方法有很多,我想个人喜好是选择其中一种的主要原因。
对于您的特殊情况,我会选择这样的东西:
public class TestC {
// Static data member, constructor does not read data from XML
private static YourDataObject obj = new YourDataObject();
public static YourDataObject getInstance(String xmlFile) {
// Read XML file
// Actually initialize the instance
obj.set...(); //
// return the instance
return obj;
}
}