有没有办法在枚举本身内设置枚举父/超类中保存的变量? (以下没有编译,但说明了我试图实现的目标)....
class MyClass{
ObjectType type;
String someValue;
public void setType(ObjectType thisType){
type = thisType;
}
enum ObjectType {
ball{
@Override
public void setValue(){
someValue = "This is a ball"; //Some value isn't accessible from here
}
},
bat{
@Override
public void setValue(){
someValue = "This is a bat"; //Some value isn't accessible from here
}
},
net{
@Override
public void setValue(){
someValue = "This is a net"; //Some value isn't accessible from here
}
};
public abstract void setValue();
}
}
然后,像这样:
MyClass myObject = new MyClass();
myObject.setType(ObjectType.ball);
完成上述操作后,“某些价值观”会被发现。现在应该将myObject的字符串设置为'这是一个球'。
有没有办法做到这一点?
答案 0 :(得分:6)
嵌套enum
类型是隐式静态的(请参阅Are java enum variables static?)。这包括声明为内部类的enum
类型,因此它们无法访问外部类的实例字段。
您无法执行enum
尝试的操作,您必须将其建模为普通课程。
答案 1 :(得分:2)
如果你希望MyClass.someValue等于enum的someValue,你可以做以下事情,但是因为someValue可以从枚举中检索到我根本不会在MyClass上有一些值,而只是从它中检索它必要时枚举
public class MyClass {
ObjectType type;
String someValue;
public void setType(ObjectType thisType) {
this.type = thisType;
this.someValue = thisType.getSomeValue();
}
enum ObjectType {
ball ("This is a ball"),
bat ("This is a bat"),
net ("This is a net");
private final String someValue;
ObjectType(String someValue) {
this.someValue = someValue;
}
public String getSomeValue() {
return someValue;
}
}
}