Java 中的父级枚举
在下面的代码示例中,我尝试测试父类中枚举的值。我得到的错误是“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将其更改为:
无需限定它。
(仅供参考,如果您将这样的示例与问题区域分开进行编译,将会有所帮助 - 在我可以编译它之前,我必须对上面的示例进行相当多的更改除了 .)
Just change it to:
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.)
由于您正在使用 theParent 中的类,因此您实际上不需要限定它。
但是,即使您不需要获得资格,但仍然有可能获得资格。
出现错误的原因是
theEnum
是一个静态内部类,但p.theEnum
限定符指示一个非静态内部类,需要 instnacep
作为实例化的一部分。此处,枚举被声明为静态,因此限定它的正确方法是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 thep.theEnum
qualifier indicates a non-static inner class which requires the instnacep
as part of instantiation. Here, the enum is declared static, so the correct way to qualify it istheParent.theEnum
.