java - 当我将枚举的构造函数设为私有(private)或默认时有什么区别?

标签 java enums

我有一个枚举类如下:

public enum TargetingName {

CONTENT("Content", "Content Targeting"), TECHNOLOGY("Technology", "Technology Targeting");

private TargetingName(String textToSelect, String textDisplayed) {
        this.textToSelect = textToSelect;
        this.textDisplayed = textDisplayed;
    }

    private String textToSelect;
    private String textDisplayed;

    public String getTextDisplayed() {
        return textDisplayed;
    }

    public String getTextToSelect() {
        return textToSelect;
    }
}

如果我不在 enum 的构造函数中写 private,它会默认吗?如果是,会有什么区别?如果否,那么如何制作默认构造函数?

最佳答案

8.9.2. Enum Body Declarations

In an enum declaration, a constructor declaration with no access modifiers is private.

除非您需要多写一个字,否则没有任何区别。

我看到开发人员放置了 private 以使其更加明确(以强调您不能在枚举之外使用枚举构造函数这一事实)。我觉得没必要。

If I don't write private in constructor of enum does it make it default?

如果“默认”是指 private,是的。

如果“默认”是指package-private,则不是。 publicprotected 都是不允许的。枚举构造函数始终是私有(private)的

8.9.2. Enum Body Declarations

It is a compile-time error if a constructor declaration in an enum declaration is public or protected (§6.6).

关于java - 当我将枚举的构造函数设为私有(private)或默认时有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58023778/

相关文章:

java - org.openqa.selenium.WebDriverException : unknown error: call function result missing 'value'

java - 在整数处找到一对字符串并相减,java

java.net.ConnectException : Connection timed out: connect error connecting to remote database

java - 快速枚举问题

swift - 更改枚举的功能

java - Android后台任务问题

java - 如何让任意IP地址连接到远程MySQL服务器?

c++ - 如何将枚举导入 C++ 中的不同命名空间?

c++ - 从 C++ 基类中的函数返回枚举

java - Swift 中的高级 Java 枚举