Java 中的父级枚举

发布于 2024-09-13 07:47:19 字数 607 浏览 0 评论 0原文

在下面的代码示例中,我尝试测试父类中枚举的值。我得到的错误是“p.theEnum 无法解析或不是字段。”,但它与我在父类中用于测试值的代码完全相同(显然没有 p.)。

我哪里出错了? :)

public class theParent {
    protected static enum theEnum { VAL1, VAL2, VAL3 };
    private theEnum enumValue = theEnum.VAL1;

    theParent() { this.theChild = new theChild(this); this.theChild.start(); }

    class theChild {
        private parentReference p;

        public theChild (theParent parent) { this.p = parent; }

        public void run() {
            // How do I access theEnum here?
            if (p.enumValue == p.theEnum.VAL1) { }
        }
    }
}

In the code example below, I'm trying to test the value of an enum in the parent class. The error I get is "p.theEnum cannot be resolved or is not a field.", but it's the exact same code I use in the parent class to test the value (without the p. obviously).

Where am I going wrong? :)

public class theParent {
    protected static enum theEnum { VAL1, VAL2, VAL3 };
    private theEnum enumValue = theEnum.VAL1;

    theParent() { this.theChild = new theChild(this); this.theChild.start(); }

    class theChild {
        private parentReference p;

        public theChild (theParent parent) { this.p = parent; }

        public void run() {
            // How do I access theEnum here?
            if (p.enumValue == p.theEnum.VAL1) { }
        }
    }
}

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

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

发布评论

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

评论(2

浴红衣 2024-09-20 07:47:19

只需将其更改为:

if (p.enumValue == theEnum.VAL1) { }

无需限定它。

(仅供参考,如果您将这样的示例与问题区域分开进行编译,将会有所帮助 - 在我可以编译它之前,我必须对上面的示例进行相当多的更改除了 .)

Just change it to:

if (p.enumValue == theEnum.VAL1) { }

There's no need to qualify it.

(Just as an FYI, it would help if you'd make samples like this compile apart from the problem area - I had to make quite a few changes aside from the one above before I could make it compile.)

ゞ记忆︶ㄣ 2024-09-20 07:47:19

由于您正在使用 theParent 中的类,因此您实际上不需要限定它。

但是,即使您不需要获得资格,但仍然有可能获得资格。

出现错误的原因是 theEnum 是一个静态内部类,但 p.theEnum 限定符指示一个非静态内部类,需要 instnace p 作为实例化的一部分。此处,枚举被声明为静态,因此限定它的正确方法是 theParent.theEnum

Since you are using the class from within theParent, you don't actually need to qualify it.

But, even though you don't need to qualify, it should still be possible to qualify.

The reason you get the error is that theEnum is a static inner class, but the p.theEnum qualifier indicates a non-static inner class which requires the instnace p as part of instantiation. Here, the enum is declared static, so the correct way to qualify it is theParent.theEnum.

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