为什么不能在 Java 中保护或公开枚举构造函数? [英] Why can't enum constructors be protected or public in Java?

查看:24
本文介绍了为什么不能在 Java 中保护或公开枚举构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整个问题都在标题中.例如:

The whole question is in the title. For example:

enum enumTest {

        TYPE1(4.5, "string1"), TYPE2(2.79, "string2");
        double num;
        String st;

        enumTest(double num, String st) {
            this.num = num;
            this.st = st;
        }
    }

构造函数可以使用 default 或 private 修饰符,但如果给定 publicprotected 修饰符,则会出现编译器错误.

The constructor is fine with the default or private modifier, but gives me a compiler error if given the public or protected modifiers.

推荐答案

将 Enum 视为具有有限数量实例的类.除了您最初声明的实例之外,永远不会有任何不同的实例.

Think of Enums as a class with a finite number of instances. There can never be any different instances beside the ones you initially declare.

因此,您不能拥有公共或受保护的构造函数,因为这将允许创建更多实例.

Thus, you cannot have a public or protected constructor, because that would allow more instances to be created.

注意:这可能不是官方原因.但对我来说,以这种方式思考 enums 最有意义.

Note: this is probably not the official reason. But it makes the most sense for me to think of enums this way.

这篇关于为什么不能在 Java 中保护或公开枚举构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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