如何实例化Java枚举

时间:2016-05-24 09:40:01

标签: java

public enum Difficulty {
EASY,   //easy game, lots of villages to spare
NORMAL, //normal game, fewer villagers & bullets
HARD;   //hard game, the wolf relocates when shot

/**
 * Returns a multi-line String describing the characteristics of this
 * difficulty level.
 */
public String toString() {
    return "Player starts in the village: " + getPlayerStartsInVillage() +
            "\nNumber of villagers: " + getVillagerCount() +
            "\nAvailable silver bullets: " + getSilverBulletCount() + 
            "\nWerewolf moves when shot: " + getWolfMovesWhenShot();
}

/**
 * Returns true if the player starts in the same area as the village for
 * this difficulty level, false otherwise.
 */
public boolean getPlayerStartsInVillage() {
    return this == EASY;
}

/**
 * Returns the initial number of villagers for this difficulty level.
 */
public int getVillagerCount() {
    switch (this) {
    case EASY: return 6;
    case NORMAL: return 4;
    default /*HARD*/: return 4;
    }
}

/**
 * Returns the number of silver bullets the player starts with in this
 * difficulty level.
 */
public int getSilverBulletCount() {
    switch (this) {
    case EASY: return 8;
    case NORMAL: return 6;
    default /*HARD*/: return 6;
    }
}

/**
 * Returns true if the werewolf moves when hit, false otherwise.
 */
public boolean getWolfMovesWhenShot() {
    return this == HARD;
}

我有这个(上面)类,我想调用它来使用下面的方法,但我不知道如何。我知道

Difficulty obj1 = new Difficulty(); 

但是返回时“无法实例化难度”。有人可以告诉我要编写什么代码来使其工作吗?

public class WereWolfenstein2D {
}

1 个答案:

答案 0 :(得分:0)

您不能以这种方式实例化枚举:

Difficulty obj1 = new Difficulty();

这是有充分理由的。

当您拥有一组固定的相关常量时,枚举就是适用的。你不想实例化一个,因为那时集合不会被修复。

你想要做的是这样的事情:

Difficulty obj1 = Difficulty.NORMAL

很高兴阅读Oracle Tutorial Java Enums