我有一个枚举类如下:
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,它会默认吗?如果是,会有什么区别?如果否,那么如何制作默认构造函数?
最佳答案
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,则不是。 public
和 protected
都是不允许的。枚举构造函数始终是私有(private)的
。
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/