public class Location {
final public static int INITIAL = 0;
final public static int PRISON = 1;
final public static int DEATH = 2;
final public static int SQUARE = 3;
private String name;
private int type;
private int section;
private int damage;
private Square square ;
// this constructor construct a Location from a name and a type.
public Location(String name, int type) {
this.name = name;
this.type = type;
}
// this constructor constructs a Location of type SQUARE from a name, section, and damage.
public Location(String name, int section, int damage) {
this.name = name;
this.section = section;
this.damage = damage;
this.square = new Square(name,section,damage);
}
// Get the square associated with this Location.
public Square getSquare() {
return square;
}
}
我想我誤解了第二個構造函數正在做什麼,因爲目前構造函數沒有對實例變量square做任何事情。如何使用構造函數在Java中初始化其他類的對象?
第二個構造函數的註釋聲明它創建了SQUARE類型的位置,但代碼未能將'type'字段設置爲SQUARE。 – FredK