我该如何在子类中定义这些生物?

时间:2014-01-17 00:59:47

标签: java inheritance enums

我有一个像这样定义的超类:

public class Creature {

    Terrain terrain;

    //symbols on cards
    boolean flyingCreature;
    boolean magicCreature;
    boolean canCharge;
    boolean rangedCombat;
    public int specialAbility = 0;

    public Creature(Terrain startTerrain, boolean flying, boolean magic, boolean charge, boolean ranged, int special){
        terrain = startTerrain;
        flyingCreature = flying;
        magicCreature = magic;
        canCharge = charge;
        rangedCombat = ranged;
        specialAbility = special;
    }
}

我的子类定义如下:

public class MountainCreature extends Creature{
    public enum Creature{
        GOBLINS, DWARVES, TROLL, GREATEAGLE, BROWNDRAGON,
        MOUNTAINMEN, GIANTROC, GIANTCONDOR, CYCLOPS, GREATHAWK,
        OGRE, BROWNKNIGHT, LITTLEROC, GIANT, MOUNTAINLION
    }

    public MountainCreature(int startTerrain, boolean flying, boolean magic, boolean charge, boolean ranged, int special){
        super(startTerrain, flying, magic, charge, ranged, special);
    }
}

我有15种不同的MountainCreatures(它们是我的枚举中的那些),并且它们各自具有构造函数中所有特征的变体。如何单独定义每个生物?我不应该在这里使用枚举吗?

2 个答案:

答案 0 :(得分:1)

我会创建MountainCreature构造函数protected,因此无法直接实例化,但将来仍可以使用子类。

如果所有生物都具有相同的属性,那么在此建议中您将不需要枚举。您可以为每个要创建的生物创建public static方法,例如

public static MountainCreature createGoblin() {
    return new MountainCreature( /* goblin-specific characteristics here */);
}

public static MountainCreature createDwarf() {
    return new MountainCreature( /* dwarf-specific characteristics here */);
}

// And so on...

或者,您可以保留枚举并创建一个采用枚举值并决定要创建哪个生物的工厂方法:

public static MountainCreature createCreature(MountainCreature.Creature type) {
    MountainCreature creature;
    switch(type) {
        case GOBLINS:
            creature = new MountainCreature( /* goblin-specific characteristics here */);
        break;
        case DWARVES:
            creature = new MountainCreature( /* dwarf-specific characteristics here */);
        break;
        // And so on...
    }
    return creature;
}

答案 1 :(得分:0)

如果他们的共同点只有生物的属性,你应该为每个生物定义类。

但是,例如,如果地精和食人魔可以生活在桥下或洞穴中,你可以使用一个名为HideCreature的类来扩展生物,然后定义一个扩展了HideCreature的类Goblin,另一个类Ogre也扩展了HideCreature。

这就是这里的概念。搜索共同点然后合并。