Why the static methods values() and valueOf() in Enum are added by the compiler and not explicitly declared in the Enum class?

StackOverflow https://stackoverflow.com/questions/15452703

  •  24-03-2022
  •  | 
  •  

Question

In reading through the Javadoc of Enum I can see a signature of valueOf() that is not what I usually use. Also the javadoc for values() method is also missing. I read that these methods are actually generated by the compiler automatically. So my question is why are these methods not declared as static methods in the Enum class itself? What is the need for the methods to be included like the way they are by the compiler? Why this extra layer of abstraction?

Was it helpful?

Solution

These methods have to be declared not in Enum, but in the Enum subclass, the enum type you're writing. They can't be added any other way, not least since static methods don't inherit the way instance methods do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top