问题
This question is closely related to my previous question on SO about using interface with enums. Essentially, I have a bunch of enums that are closely related, and they all implement a common interface.
The interface is called Sections and the enums are called SectionA, SectionB, etc. I have other classes which have fields like List<Sections> and Map<Sections, String>. Now, to populate these fields, I would like to have access to valueOf(String), i.e. I would like to be able to say something like
Map<Sections, String> sectionsMap = new HashMap<Sections, String>();
for (String s : someStringList) {
try {
sectionsMap.put(Sections.valueOf(s), someOtherFunctionReturningString(s));
} catch (IllegalArgumentException e) {
e.printStackTrace(); // if s doesn't match any enum
}
}
I also have my own static methods in the enums SectionA, SectionB, etc. (This is because these enums all have a single java.util.regex.Pattern field, and my static method is a generalization of the valueOf(String) method based on pattern matching.)
So, my question is this:
How can I retain access to the static methods of these enums while also having their generalization at the interface level?
I am open to other design decisions (in fact, I am currently getting rid of the whole enum idea and creating classes that implement Sections and extend an abstract class AbstractSection), but I am quite curious about how others make their decisions in similar situations. I have asked this question with the hope that someone out there has better ideas than those in my head.
回答1:
You cannot override an static method.
A subclass may name a static method the same as that of the superclass, however super is a non-static operator.
You could have multiple methods which perform two different functions, but they would need different names.
来源:https://stackoverflow.com/questions/21789191/how-to-extend-static-methods-for-enums-implementing-an-interface