Java variables are not extensible, but can implement interfaces.
You can often get the best of both worlds by defining an interface that providers can implement, and an enumeration that implements it, and contains frequently used instances that users can use directly:
public interface Pet { public String talk(); }
public enum CommonPet implements Pet { CAT("Meow!"), DOG("Woof! Woof!"); private final String cry; CommonPet(String cry) { this.cry = cry; } @Override public String talk() { return cry; } }
The API that was used to receive instances of the source enumeration should now take any instance of the interface.
Users can provide their own implementations using the same template:
public enum UncommonPet implements Pet { LION; @Override public String talk() { return "Roar!"; } }
Finally, there is no requirement that all implementations be enumerations, so in more complex cases, the user can implement the interface as a full-fledged class:
public class Parrot implements Pet { private String phrase = "Pieces of eight!"; @Override public String talk() { return phrase; } public void teach(String phrase) { this.phrase = phrase; } }
Andrea
source share