项目构造函数中的 Java Enum 私有(private)方法

标签 java enums inner-classes

public enum Parent {
    item1(1){

        public void testing() {
            add();
            multiply();
            minus(); // error here!!!
        } 

    }, item2(2);

    private int i ;
    Parent(int i){
        this.i = i;
    }

    public void setI(int i ){
        this.i = i;
    }
    public int getI(){
        return i;
    }

    public void multiply(){

    }
    protected void add(){

    }

    private void minus(){

    }
}

如你所见,它们在同一个类中,为什么 minus() 不能在内部使用?通常内部类可以访问外部类中的私有(private)方法/字段吗?

最佳答案

为了能够从 item1 访问 minus(),您必须将其设为 protected(或 public).

考虑 Parentitem1 的正确方法是将其作为基类和子类。

来自JLS :

The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type.

关于项目构造函数中的 Java Enum 私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13641019/

相关文章:

grails - 如何在g :select?中将i18n与Grails/Groovy枚举一起使用

java - 在创建监听器时省略空函数签名

Java 枚举和嵌套类

java - 在 Java 中使用大型内部类不好吗?

typescript - 我可以有一个对象枚举吗?

java - 在 Java DSL 中为 apache Camel 路线编写自定义方法

java - Hibernate ConstraintViolationException : could not insert, SQL 错误

java - Jackson ObjectMapper 在转换为 POJO 时忽略某些键

swift - 继承中的枚举

java - applicationContext.xml 中的数据源 bean 定义