I was very surprised by the output of the following code:
Country class
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); } public static Country getCountry(String name) { return countries.get(name); } public static void register(Country country) { countries.put(country.name, country); } @Override public String toString() { return name; } 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); } } }
Main method
System.out.println(Country.getCountry("Spain"));
Exit
zero
Is there any clean way to force a class that extends the country to load, so does the country map contain all instances of the country?
eliocs
source share