This question is similar to this one, but I'm not satisfied with its answer. Why is the values()-method of every enum in Java implicit and static? Couldn't it just be defined as:
public final native T[] values();
I have an interface that is exclusively implemented by enums, but because the implicit method is static, i can't even define values() in that interface.
CodePudding user response:
Say you defined enum MyEnum
.
That must be static, because you want to access all values with MyEnum.values()
.
And as values()
must be static it cannot use the generic parameter (enum MyEnum extends Enum<MyEnum>
).
So don't define an interface for your enums with a method named values
. Find another appropriate name.
CodePudding user response:
It has to be static
: Because... that's the point of the method. Given an enum type, let's say CardSuit
, you'd want to invoke CardSuit.values()
, not CardSuit.SPADES.values()
, that makes no sense.
It cannot be native
: native
, specifically, means: "The actual code for this method is defined in C" (or at any rate, in a natively compiled file that has been .loadLibrary
ied in, or has been auto-loaded in by the JVM itself). The implementation of the values()
method isn't done 'in C'.
I have an interface that is exclusively implemented by enums, but because the implicit method is static, i can't even define values() in that interface.
Static methods don't 'do' inheritance. They live outside of it. It makes the most sense to think of static methods as not participating in the type system at all; they must be written inside types only because java's namespacing system piggybacks on the type system. They cannot be inherited, you can't override them. The definition of final
on a static
method is daft (a holdover from the Java 1.0 specs that aren't worth fixing at this point).
Why do you think the much-derided concept of the Factory
exists? That's taking the 'class' concept and making a separate type hierarchy for that concept, so that you can have an instance that represents the class: You have, say, a Person
class, as well as a PersonFactory
class. An instance of PersonFactory
is a lot like the concept Person.class
, except Person.class
cannot 'do' inheritance, and static methods cannot be interfaced or overridden in any way. Whereas with the factory stuff, the actual factory is an instance, thus the relevant methods can be instance methods, and thus you can have em implement interfaces and the like.
At any rate, given that values()
is static and doesn't make sense as non-static, defining an interface that your enums are meant to implement just does not make sense. At best, the factory equivalent for your enums could implement it: values()
is a question you ask of the entire type itself. Which is not what interface methods are for! Interface methods are questions you can ask of a specific instance of the type.