2015-07-20 45 views
1
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中初始化其他类的对象?

回答

0

在你的第二个构造函数,你就必须与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属性的初始化,对我来说似乎没问题。您可以在构造函数内创建其他类的实例,并根据需要将它们分配给属性。

0

在您的第二个构造函数中,您只需从您提供给构造函数的参数初始化您的Location类的属性 - private Square square

初始化对象/非原始(eg.- square这里)类型是完全用Java有效像初始化其他基本类型(例如 - typesection等在这里。)

+0

第二个构造函数的注释声明它创建了SQUARE类型的位置,但代码未能将'type'字段设置为SQUARE。 – FredK

-1

你有一个问题:你的第一个构造函数对Square引用没有任何作用,所以它是空的。

试试这样说:

/** 
* @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; 
    } 
} 
+0

你用type来初始化section? – Fildor

+0

急速,就是这样。我会解决它。 – duffymo

相关问题