【发布时间】:2015-07-26 20:28:17
【问题描述】:
我正在自学 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());
}
}
由于某种原因,它正在打印“Large Rat”而不是“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;
}
}
【问题讨论】:
-
每个“生物”的参数代表生物的属性,例如健康、等级、力量、防御等。
-
你能显示
Creature类吗,可能会从那里返回相同的实例 -
我怀疑静态字段(这意味着它是由类共享的),大多数初学者倾向于使他们的字段静态只是为了摆脱编译问题,他们被要求不要引用非静态内容从主要方法。顺便说一句,总是看到“Large Rat”可能还有其他原因,但如果没有看到您的代码,我们只能猜测。
-
听起来很合理,可能 CreatureName 是静态的。
-
不用看你的代码我就可以告诉你
Creature的名称存储在static变量中,这意味着它在所有实例之间共享的Creature。将其设为非静态将解决此问题。
标签: java