繁体   English   中英

从内部嵌套枚举访问外部类

[英]access outer class from inner nested enum

有办法进入外面吗?

public class OuterClass  {
    String data;

    public void outerMethod(String data) {
         this.data = data;
    }

    public enum InnerEnum {
        OPTION1("someData"),
        OPTION2("otherData");

        InnerEnum(String data) {
              // Does not work:             
              OuterClass.this.outerMethod(data);
        }
    }
}

正如埃里克所说,枚举是隐含的。 要做你想做的事,添加一个方法,调用oc.outerMethod(data) callOuterMethod(OuterClass oc)来做你想要的:

public enum InnerEnum {
    OPTION1("someData"),
    OPTION2("otherData");

    final String data;

    InnerEnum(String data) {
       this.data = data;             
    }

    void callOuterMethod(OuterClass oc) {
        oc.outerMethod(data);
    }
}

不能这样做。 枚举是隐式静态的,即使你没有声明它。 看到类似的问题/答案:

“嵌套的枚举类型是隐式静态的。允许将嵌套的枚举类型显式声明为静态是允许的。”

在Java中,类静态中的枚举类型是什么?

我相信你会把对象实例与类型混淆。 你声明的是两种嵌套类型。 这与两个嵌套对象实例不同。

使用类型操作时,关键字this没有意义。 它只在处理对象实例时具有意义。 因此,如果您尝试从内部类型调用外部类型的实例方法,则需要引用外部类型的实例。

但是,如果将外部类型的方法设置为static,则可以从嵌套类型调用静态方法,而无需引用外部类型的实例。 请记住,如果这样做,该方法“对所有实例都相同” - 意味着它与OuterClass的所有实例共享任何状态 - 因此它只能访问该类型的静态成员。

在下面的示例中, outerMethod声明为static,因此可以从嵌套类型调用它,而无需引用outerMethod的实例。 但是,通过这样做,它无法再访问私有实例成员data (当然没有引用实例)。 您可以声明一个静态成员staticData并访问它,但请记住,该成员将由所有OuterClass实例和outerMethod的所有invokations共享。

public class OuterClass  {

        String data;                 // instance member - can not be accessed from static methods
                                     //   without a reference to an instance of OuterClass

        static String staticData;    // shared by all instances of OuterClass, and subsequently
                                     //   by all invocations of outerMethod

        // By making this method static you can invoke it from the nested type 
        //  without needing a reference to an instance of OuterClass. However, you can
        //  no longer use `this` inside the method now because it's a static method of
        //  the type OuterClass
    public static void outerMethod(String data) {

            //this.data = data;  --- will not work anymore

            // could use a static field instead (shared by all instances)
            staticData = data;
    }

    public enum InnerEnum {
        OPTION1("someData"),
        OPTION2("otherData");

        InnerEnum(String data) {
                    // Calling the static method on the outer type
                    OuterClass.outerMethod(data);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM