为什么Enum中的静态方法values()和valueOf()是由编译器添加的,没有在Enum类中显式声明? [英] Why the static methods values() and valueOf() in Enum are added by the compiler and not explicitly declared in the Enum class?

查看:176
本文介绍了为什么Enum中的静态方法values()和valueOf()是由编译器添加的,没有在Enum类中显式声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读枚举的Javadoc时,我可以看到一个签名 valueOf() 这不是我通常使用的。另外还缺少值()方法的javadoc。我读到这些方法实际上是由编译器自动生成的。所以我的问题是为什么这些方法没有在 Enum 类中声明为静态方法?需要像编译器一样包含方法的内容?为什么这个额外的抽象层?

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?

推荐答案

这些方法必须在枚举,但在枚举子类中,您正在撰写的枚举类型。他们不能以任何其他方式添加,特别是因为静态方法不会继承实例方法的做法。

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.

这篇关于为什么Enum中的静态方法values()和valueOf()是由编译器添加的,没有在Enum类中显式声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆