在 Java 中,类中的枚举类型是静态的吗? [英] In Java, are enum types inside a class static?

查看:32
本文介绍了在 Java 中,类中的枚举类型是静态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
    }
}

推荐答案

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

Yes, nested enums are implicitly static.

来自 语言规范部分 8.9:

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

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

这篇关于在 Java 中,类中的枚举类型是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆