2015-07-20 79 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

相關問題