[英]How to use a constructor to initialize a different class's object in Java?
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;
}
}
我想我误解了第二个构造函数在做什么,因为当前该构造函数对实例变量平方没有任何作用。
在第二个构造函数中,您只是在初始化属性-根据提供给构造函数的参数, Location
类的private Square square
。
初始化对象/非原始类型(例如-这里的square
)在Java中是完全有效的,就像初始化其他原始类型(例如-此处的type
, section
等)一样
在第二个构造函数中,您只需要使用Location.SQUARE
初始化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.type = Location.SQUARE;
this.square = new Square(name,section,damage);
}
现在您班级的属性将保持一致。
关于square
属性的初始化,对我来说似乎还可以。 您可以在构造函数中创建其他类的实例,并根据需要将其分配给属性。
您有一个问题:您的第一个构造函数对Square引用不执行任何操作,因此它为null。
像这样尝试:
/**
* @link http://stackoverflow.com/questions/31523704/how-to-use-a-constructor-to-initialize-an-different-classs-object-in-java
* User: mduffy
* Date: 7/20/2015
* Time: 3:07 PM
*/
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;
// No idea what damage ought to be. Is that your type?
public Location(String name, int type) {
this(name, Location.SQUARE, type);
}
public Location(String name, int section, int damage) {
this.name = name;
this.section = section;
this.damage = damage;
this.square = new Square(name, section, damage);
}
public Square getSquare() {
return square;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.