的實例我很驚訝下面的代碼的輸出:如何強制靜態字段
國家類
public class Country {
private static Map<String, Country> countries = new HashMap<String, Country>();
private final String name;
@SuppressWarnings("LeakingThisInConstructor")
protected Country(String name) {
this.name = name;
register(this);
}
/** Get country by name */
public static Country getCountry(String name) {
return countries.get(name);
}
/** Register country into map */
public static void register(Country country) {
countries.put(country.name, country);
}
@Override
public String toString() {
return name;
}
/** Countries in Europe */
public static class EuropeCountry extends Country {
public static final EuropeCountry SPAIN = new EuropeCountry("Spain");
public static final EuropeCountry FRANCE = new EuropeCountry("France");
protected EuropeCountry(String name) {
super(name);
}
}
}
主要方法
System.out.println(Country.getCountry("Spain"));
輸出
空
是否有強迫延伸到加載國家,所以國家地圖包含所有國家的實例類的任何干淨的方式?
+1。請注意,靜態塊必須在國家代碼或包含main的類中。 – Tarlog 2011-05-11 11:43:10
唯一的問題是你失去了EuropeCountry.SPAIN和EuropeCountry.FRANCE的參考文獻。 – eliocs 2011-05-11 14:24:52