gpt4 book ai didi

java - Java 枚举成员

转载 作者:行者123 更新时间:2023-11-30 06:12:25 28 4
gpt4 key购买 nike

我是 Java 新手。使用此代码:

public class MyClass{
enum State {STATE1, STATE2, STATE3}
State curState;
...
public MyClass(){
curState=STATE1;
}
}

我得到错误

STATE1 cannot be resolved to variable

如果我将 STATE1 更改为 State.STATE1 一切正常,但我不想每次都写枚举名称!我不明白为什么我必须这样做。枚举在 MyClass 范围内声明。

最佳答案

一种可能的解决方案是使用静态导入。例如,如果以上所有内容都在 pkg 包中,则:

package pkg;

import static pkg.MyClass.State.*;

public class MyClass {
enum State {
STATE1, STATE2, STATE3
}

State curState;

// ...
public MyClass() {
curState = STATE1;
}
}

根据 Static Import Tutorial :

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually or en masse.

关于java - Java 枚举成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32923643/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com