简体   繁体   English

为什么枚举引用变量不能单独声明在方法之外?

[英]Why enum reference variables cannot be declared outside method on its own?

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. [A] 当我自己创建一个枚举引用变量时,我遇到了一个语法错误。 However, [B] When I join this reference variable to an enum constant, it is somehow fine.但是,[B] 当我将此引用变量连接到枚举常量时,它在某种程度上很好。

This situation is further complicated when I experiment with putting [A] and [B] inside the main method - as [X] and [Y].当我尝试将 [A] 和 [B] 放在 main 方法中时,这种情况会更加复杂 - 作为 [X] 和 [Y]。

INSIDE MAIN METHOD:内部主要方法:

BOTH [X] and [Y] are fine. [X] 和 [Y] 都可以。 I am able to create a reference variable [X] exactly as in [A], but without error.我能够像在 [A] 中一样创建引用变量 [X],但没有错误。

I therefore think the source of the problem is that [A] is outside main method, but [X] is within method.因此,我认为问题的根源在于 [A] 在主要方法之外,但 [X] 在方法内。

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>
    }
}

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 ; tp =周围的{}称为实例初始化器 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.这些相对不常见,并且有些混乱,因此您应该更喜欢直接在字段上分配(也许定义一个方法来封装必要的逻辑),或者在构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM