问题描述
我用一个私有成员变量创建了一个枚举。
当我尝试访问成员变量时,编译状态为无法静态引用非静态字段memberVariable。
I created a enum with one private member variable.When i try to access the member variable the compiles states 'Cannot make a static reference to the non-static field memberVariable'.
如果该变量不是私有变量(例如,受保护或受包保护),则可以正常编译。我不了解变量的范围与实现的抽象函数的类型(静态,非静态)有什么关系。
If the variable is not private (e.g. protected or package protected) it compiles fine. I don't understand what the scope of the variable has to do with the type (static, non static) of the implemented abstract function.
有人能启发我吗?
public enum EnumWithAbstractMethodAndMembers {
TheOneAndOnly(1) {
@Override
public int addValue(final int value) {
return memberVariable + value;
}
};
private final int memberVariable;
private EnumWithAbstractMethodAndMembers(final int memberVariable) {
this.memberVariable = memberVariable;
}
abstract int addValue(int value);
}
推荐答案
错误消息令人困惑。
问题是当您提供枚举值代码时,您正在创建枚举的匿名子类。 (其类为 EnumWithAbstractMethodAndMembers $ 1
)子类无法访问其超类的私有成员,但是嵌套类可以通过生成的访问器方法访问。您应该能够访问私有字段,并且它给您的错误消息似乎具有误导性。
The problem is that when you give an enum value code, you are creating an anonymous sub class of the enum. (Its class will be EnumWithAbstractMethodAndMembers$1
) A sub-class cannot access the private members of its super-class, however nested classes can via generated accessor method. You should be able to access the private field, and the error message it gives you appears to be mis-leading.
BTW您可以使用此功能,但不能这样做
BTW You can use this, but you shouldn't need to IMHO.
public int addValue(final int value) {
return super.memberVariable + value;
}
这里是一个较短的例子我将在错误消息中记录为错误,因为它不会导致问题的解决。
Here is a shorter example I will log as a bug in the error message as it doesn't lead to a solution to the problem.
public enum MyEnum {
One {
public int getMemberVariableFailes() {
// error: non-static variable memberVariable cannot be referenced from a static context
return memberVariable;
}
public int getMemberVariable2OK() {
return memberVariable2;
}
public int getMemberVariableOK() {
return super.memberVariable;
}
};
private final int memberVariable = 1;
final int memberVariable2 = 1;
}
根据汤姆·霍金(Tom Hawkin)的反馈,此示例将获得相同的错误消息。
Based on Tom Hawkin's feedback, this example gets the same error message.
public class MyNotEnum {
// this is the static context in which the anonymous is created
public static final MyNotEnum One = new MyNotEnum() {
public int getMemberVariableFailes() {
// error: non-static variable memberVariable cannot be referenced from a static context
return memberVariable;
}
public int getMemberVariableOK() {
return super.memberVariable;
}
};
private final int memberVariable = 1;
}
进行比较
public class MyNotEnum {
public class NestedNotEnum extends MyNotEnum {
public int getMemberVariableFailes() {
// compiles just fine.
return memberVariable;
}
public int getMemberVariableOK() {
return super.memberVariable;
}
}
private final int memberVariable = 1;
}
这篇关于无法静态引用非静态字段memberVariable与private变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!