为什么是印刷"大鼠"而不是" Rat"

时间:2015-07-26 20:28:17

标签: java

我自学了java中的类,并决定尝试创建自己的类并在程序中使用它。首先,我有以下代码:

public class Simulator {
    public static void main(String[] args){

        Creature rat = new Creature(1, 12, 3, 1, 2, 1, 3);
        Creature poisonRat = new Creature(2, 16, 5, 4, 3, 4, 5);
        Creature largeRat = new Creature(5, 24, 10, 7, 4, 7, 10);

        rat.setCreatureName("Rat");
        poisonRat.setCreatureName("poisonous Rat");
        largeRat.setCreatureName("Large Rat");

        System.out.println(rat.getCreatureName());
    }

}

出于某种原因它是印刷"大鼠"而不是印刷" Rat"而且我不知道为什么。我是处理课程的新手,所以我不知道自己在做什么。有什么想法吗?

这里是生物类:

public class Creature {

    private String creatureName;
    private static int creatureLvl;
    private static double healthPoints;
    private static double strength;
    private static double magic;
    private static double defense;
    private static double magicDefense;
    private static double speed;

    public Creature (int lvl, double hp, double str, double mag, double def,      double magDef, double spd){
        creatureLvl = lvl;
        healthPoints = hp;
        strength = str;
        magic = mag;
        defense = def;
        magicDefense = magDef;
        speed = spd;
    }

    public String getCreatureName() {
        return creatureName;
    }

    public void setCreatureName(String creatureName) {
        creatureName = creatureName;
    }


}

1 个答案:

答案 0 :(得分:2)

我认为您已将creatureName类中的Creature声明为static字段:

private static String creatureName;

这意味着它是一个在类的所有实例之间共享的字段;如果您通过一个实例更改字段,则将在所有其他实例中更改该字段。改为

private String creatureName;

你应该没事。

编辑:

此外,在setter方法中,如果字段与参数同名,则需要使用this.

public void setCreatureName(String creatureName) {
    this.creatureName = creatureName;
}