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

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

问题描述

由于枚举构造函数只能由其常量调用,那么为什么它被允许为package-private?

解决方案

构造函数实际上不是package-private ...它隐式地是 private 接口方法隐式的方式 public even如果你不添加关键字。



JLS的相关部分(§8.8.3)状态:


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



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



如果枚举类型的构造函数(§ 8.9)被声明为 public protected



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

解决方案

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.

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.

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

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

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

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