英文:
Why enum reference variables cannot be declared outside method on its own?
问题
我对于创建枚举类型的引用变量的规则感到困惑。
**在主方法之外:**
[A] 当我单独创建一个枚举引用变量时,会收到语法错误的提示。
然而,
[B] 当我将这个引用变量与枚举常量连接在一起时,却没有问题。
当我尝试将 [A] 和 [B] 放在主方法内部时,就像 [X] 和 [Y]。
**在主方法内部:**
[B] 和 [Y] 都没有问题。我能够创建一个与 [A] 类似的引用变量 [X],但却没有错误。
因此,我认为问题的根源在于 [A] 在主方法之外,而 [X] 在方法内部。
我可以在方法内部创建枚举的引用变量,但在方法外部这样做会产生语法错误。有人知道为什么会这样吗?非常感谢。
enum Transport {
CAR, TRUCK, AIRPLANE, TRAIN, BOAT
}
public class EnumDemo {
Transport tp; // <A> - 在 ';' 处有语法错误。
tp = Transport.AIRPLANE;
Transport tb = Transport.AIRPLANE; // <B>
public static void main(String[] args) {
Transport tp; // <X> 但这是可以的。
tp = Transport.AIRPLANE;
Transport tb = Transport.AIRPLANE; // <Y>
}
}
英文:
I am confused by the rules when it comes to creating reference variables to enum types.
OUTSIDE MAIN METHOD:
[A] When I create a reference variable to enum on its own, I am greeted with a syntax error.
However,
[B] When I join this reference variable to an enum constant, it is somehow fine.
This situation is further complicated when I experiment with putting [A] and [B] inside the main method - as [X] and [Y].
INSIDE MAIN METHOD:
BOTH [X] and [Y] are fine. I am able to create a reference variable [X] exactly as in [A], but without error.
I therefore think the source of the problem is that [A] is outside main method, but [X] is within method.
I am able to create reference variable to enum inside a method, but doing so outside will produce syntax error. Does anyone know why this is so? Thank you very much.
enum Transport {
CAR, TRUCK, AIRPLANE, TRAIN, BOAT
}
public class EnumDemo {
Transport tp; // <A> - syntax error on ';'
tp = Transport.AIRPLANE;
Transport tb = Transport.AIRPLANE; // <B>
public static void main(String[] args) {
Transport tp; // <X> but this is fine.
tp = Transport.AIRPLANE;
Transport tb = Transport.AIRPLANE; // <Y>
}
}
答案1
得分: 1
这与它是枚举无关:你不能在方法或代码块之外编写语句,只能声明成员。
以下方式有效:
public class EnumDemo {
Transport tp;
{
tp = Transport.AIRPLANE;
}
//...
{}
在 tp =
周围被称为实例初始化程序;这些相对较少见,有些令人困惑,所以你应该更倾向于直接在字段上赋值(或者定义一个方法来封装必要的逻辑),或者在构造函数中赋值。
英文:
This is nothing specific to it being an enum: you just can't write statements outside methods or block, you can only declare members.
This would work:
public class EnumDemo {
Transport tp; // <A> - syntax error on ';'
{
tp = Transport.AIRPLANE;
}
//...
The {}
around tp =
is called an instance initializer; these are relatively uncommon, and somewhat confusing, so you should prefer assigning directly on the field (perhaps defining a method to encapsulate necessary logic), or in a constructor.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论