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

发布于 2024-07-14 21:45:25 字数 586 浏览 7 评论 0原文

我似乎无法从枚举内部访问周围类的实例成员,就像我可以从内部类内部访问一样。 这是否意味着枚举是静态的? 是否可以访问周围类实例的范围,或者我是否必须将实例传递到我需要的枚举方法中?

public class Universe {
    public final int theAnswer;

    public enum Planet {
        // ...
        EARTH(...);
        // ...

        // ... constructor etc.

        public int deepThought() {
            // -> "No enclosing instance of type 'Universe' is accessible in this scope"
            return Universe.this.theAnswer;
        }
    }

    public Universe(int locallyUniversalAnswer) {
        this.theAnswer = locallyUniversalAnswer;
    }
}

I can't seem to access instance members of the surrounding class from inside an enum, as I could from inside an inner class. Does that mean enums are static? Is there any access to the scope of the surrounding class's instance, or do I have to pass the instance into the enum's method where I need it?

public class Universe {
    public final int theAnswer;

    public enum Planet {
        // ...
        EARTH(...);
        // ...

        // ... constructor etc.

        public int deepThought() {
            // -> "No enclosing instance of type 'Universe' is accessible in this scope"
            return Universe.this.theAnswer;
        }
    }

    public Universe(int locallyUniversalAnswer) {
        this.theAnswer = locallyUniversalAnswer;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴情换悲伤 2024-07-21 21:45:25

是的,嵌套枚举是隐式静态的。

来自语言规范第 8.9 节

嵌套枚举类型是隐式的
静止的。 允许
显式声明嵌套枚举类型
保持静态。

Yes, nested enums are implicitly static.

From the language specification section 8.9:

Nested enum types are implicitly
static. It is permissable to
explicitly declare a nested enum type
to be static.

天生の放荡 2024-07-21 21:45:25

制作实例级(非静态)内部枚举类是没有意义的 - 如果枚举实例本身与外部类绑定,它们就会破坏枚举保证 -

例如,如果您有

public class Foo {
   private enum Bar {
        A, B, C;
   } 
}

正确的枚举值作为常量,(伪代码,忽略访问限制)

Bar b1 = new Foo().A
Bar b2 = new Foo().A

b1 和 b2 必须是相同的对象。

It wouldn't make sense to make an instance-level (non-static) inner enum class - if the enum instances were themselves tied to the outer class they'd break the enum guarantee -

e.g. if you had

public class Foo {
   private enum Bar {
        A, B, C;
   } 
}

For the enum values to properly act as constants, (psuedocode, ignoring access restrictions)

Bar b1 = new Foo().A
Bar b2 = new Foo().A

b1 and b2 would have to be the same objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文