繁体   English   中英

如何在Java中声明和使用静态枚举

[英]How to declare and use static enum in Java

我在SO上搜索有关我的问题的信息,但找不到与我的情况相符的相关示例。

public class Game{
        static enum Tile
              {
                static //Syntax error, insert "Identifier" to complete EnumConstantHeader
                {
                  DIRT = new Tile("DIRT", 1); //Cannot instantiate the type Game.Tile
                  GRASS = new Tile("GRASS", 2);
                  ROCK = new Tile("ROCK", 3);
                  EXIT = new Tile("EXIT", 4);
                  PLAYER = new Tile("PLAYER", 5);
                  PLAYER_LEFT = new Tile("PLAYER_LEFT", 6);
                  PLAYER_RIGHT = new Tile("PLAYER_RIGHT", 7);
                 //For all above declared fields, I am getting this compile time errors :
                 /*
                  Multiple markers at this line
                     - Cannot instantiate the type 
                       Game.Tile
                      - DIRT cannot be resolved to a 
                       variable
                 */
                  Tile[] arrayOfTile = new Tile[8];
                  arrayOfTile[0] = EMPTY;
                  arrayOfTile[1] = DIRT;
                  arrayOfTile[2] = GRASS;
                  arrayOfTile[3] = ROCK;
                  arrayOfTile[4] = EXIT;
                  arrayOfTile[5] = PLAYER;
                  arrayOfTile[6] = PLAYER_LEFT;
                  arrayOfTile[7] = PLAYER_RIGHT;
                  $VALUES = arrayOfTile;
                }
              }
}

就我而言,我已经声明了上述枚举。 但是我收到了很多编译错误,这些错误已作为注释插入到上面的代码中。 有人能指出我正确的方向来解决这个问题吗?

我会遵循标准的枚举教程

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

看看Planet的示例

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

有一个为您定义的values()方法。 您不需要自己做。

您缺少瓷砖的构造函数

暂无
暂无

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

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