1
正在讀的書叫緊急設計和單身的話題......Java的嵌套類
public class MyApp {
private class SingletonHolder {
public Object singleton;
static {
singleton = new Object();
}
}
}
然後蝕不斷抱怨靜態{}
在讀的Java,類應該可以有多個靜態初始值設定項。那麼我怎樣才能做出上述工作呢?
/tmp/jc_4873/MyApp.java:5: non-static variable singleton cannot be referenced from a static context
singleton = new Object();
^
/tmp/jc_4873/MyApp.java:4: inner classes cannot have static declarations
static {
^
2 errors
public class MyApp {
private class SingletonHolder {
public static Object singleton;
static {
singleton = new Object();
}
}
}
/tmp/jc_8488/MyApp.java:3: inner classes cannot have static declarations
public static Object singleton;
^
/tmp/jc_8488/MyApp.java:4: inner classes cannot have static declarations
static {
^
2 errors
public class MyApp {
private static class SingletonHolder {
public static Object singleton;
static {
singleton = new Object();
}
}
}
+1同意,我還會補充說SingletonHolder應該是一個靜態類。 – 2010-12-11 04:29:54