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

查看:297
本文介绍了为什么枚举构造函数在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;
        }
    }

构造函数使用默认值或 private modifier,但如果给定 public protected 修饰符。

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

推荐答案

将枚举视为具有有限数量实例的类。

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.

注意:这可能不是官方原因。但这对我来说最有意义的是以这种方式想出枚举

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

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