我对以下代码的输出感到非常惊讶:
国家级
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
主要方法
System.out.println(Country.getCountry("Spain"));
Run Code Online (Sandbox Code Playgroud)
产量
空值
是否有任何干净的方法强制扩展国家/地区的类,以便国家地图包含所有国家/地区实例?
是的,使用静态初始化程序块:
public class Country {
private static Map<String, Country> countries = new HashMap<String, Country>();
static {
countries.put("Spain", new EuroCountry("Spain"));
}
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1592 次 |
| 最近记录: |