की इन्स्टेन्शियशन मजबूर करने के लिए मैं निम्नलिखित कोड के उत्पादन की काफी हैरान था:कैसे स्थिर क्षेत्रों
देश वर्ग
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। बस ध्यान दें कि स्थिर ब्लॉक या तो देश कोड में या कक्षा में मुख्य होना चाहिए। – Tarlog
केवल समस्या यह है कि आप यूरोप कैंट्री खो देते हैं। स्पेन और यूरोपकंट्री। फ़्रांस संदर्भ। – eliocs