为什么枚举可以有一个包私有构造函数? [英] Why can a enum have a package-private constructor?

查看:28
本文介绍了为什么枚举可以有一个包私有构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然枚举构造函数只能由它的常量调用,为什么还允许它是包私有的?

Since an enum constructor can only be invoked by its constants, why is it then allowed to be package-private?

推荐答案

构造函数实际上不是包私有的......它是隐式private接口方法隐式public<的方式/code> 即使您不添加关键字.

The constructor actually isn't package-private... it's implicitly private the way interface methods are implicitly public even if you don't add the keyword.

JLS 的相关部分(§8.8.3) 声明:

The relevant section of the JLS (§8.8.3) states:

如果没有为普通类的构造函数指定访问修饰符,则构造函数具有默认访问权限.

If no access modifier is specified for the constructor of a normal class, the constructor has default access.

如果没有为枚举类型的构造函数指定访问修饰符,则构造函数为private.

If no access modifier is specified for the constructor of an enum type, the constructor is private.

如果枚举类型(第 8.9 节)的构造函数声明为 publicprotected,则会导致编译时错误.

It is a compile-time error if the constructor of an enum type (§8.9) is declared public or protected.

这篇关于为什么枚举可以有一个包私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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