2014-10-28 97 views
-1

我有那些2層的構造函數:構造函數名稱相同,但不同的簽名不運行

public StockItem(Long id, String name, String desc, double price) { 
    this.id = id; 
    this.name = name; 
    this.description = desc; 
    this.price = price; 
} 

public StockItem(Long id, String name, String desc, double price, int quantity) { 
    this.id = id; 
    this.name = name; 
    this.description = desc; 
    this.price = price; 
    this.quantity = quantity; 
} 

在另一類這樣做:

StockItem item2 = new StockItem(); 
item2.setId(Long.parseLong(idField.getText())); 
item2.setName(nameField.getText()); 
item2.setDescription(descField.getText()); 
item2.setPrice((double) Math.round(Double.parseDouble(priceField.getText()) * 10)/10); 
item2.setQuantity(Integer.parseInt(quantityField.getText())); 
System.out.println(item2); 

輸出是:

id, name, desc, price 

爲什麼不把數量放入item2? 如果我這樣做:

System.out.println(Integer.parseInt(quantityField.getText())); 

它能給我的數量。

任何人都可以告訴我爲什麼它沒有意識到使用第二個StockItem構造函數。即使在刪除第一個StockItem構造函數後也嘗試過。

+1

你甚至不*調用構造函數,你可以調用setter。你的二傳手是否壞了? – 2014-10-28 12:55:56

回答

1

在您的toString()方法StockItem中,您還必須包括quantity。例如:

public String toString() { 
    return id + ", " + name + ", " + description + ", " + price + ", " + quantity; 
} 

這樣,當你做System.out.println(item2);,該toString()將包括在結果中quantity被調用。

+0

它可以工作,但是如果使用4簽名構造函數的其他地方,我可以使用4個簽名創建另一個toString,而不需要數量? – OFFLlNE 2014-10-28 12:59:58

+0

如果你有'toString()'簽名,沒有。 – 2014-10-28 13:00:43

+0

@kocko如果您需要這樣做,只需將數量初始化爲「」空字符串,並且如果它們使用其他構造函數,它將不會打印任何內容。 – brso05 2014-10-28 13:05:00

4

對於一個你沒有使用你的問題中顯示的構造函數。您正在創建一個新對象,然後使用setter設置這些字段。你可能想看看你的班級的setQuantity方法,看看它在做什麼。你在這裏不使用任何構造函數。

嘗試這樣的事情來初始化對象:

StockItem item2 = new StockItem(Long.parseLong(idField.getText()), nameField.getText(), descField.getText(), (double) Math.round(Double.parseDouble(priceField.getText()) * 10)/10, Integer.parseInt(quantityField.getText())); 

實際上,它將使用您的構造函數。

另請參見Your StockItem類的toString()方法。這可能不是打印數量。您需要將數量字段添加到toString()方法輸出中。

+1

我用過它,它給了我相同的輸出。 這就是爲什麼不知道這兩者之間存在差異。 – OFFLlNE 2014-10-28 13:22:04

+0

是的,這是有區別的。 setters設置單個字段,而構造函數用於初始化整個對象。無論哪種方式使用默認構造函數,然後設置器或使用自定義構造函數,但更好的方法是使用您的自定義構造函數。那是他們的。 – brso05 2014-10-28 13:24:18

0

您使用它的構造函數不在您在此處顯示的構造函數中。你確定你可以在沒有參數的情況下創建新的構造函數嗎?如果我沒有錯,你應該像這樣使用它們。如果你想使用第一構造:

Long id = Long.parseLong(idField.getText()); 
String name = nameField.getText(); 
String desc = descField.getText(); 
double price = (double) Math.round(Double.parseDouble(priceField.getText()); 

StockItem stockItemUsingFirstConstructor = new StockItem(id, name, desc, price); 

如果你想使用第二構造:

Long id = Long.parseLong(idField.getText()); 
String name = nameField.getText(); 
String desc = descField.getText(); 
double price = (double) Math.round(Double.parseDouble(priceField.getText()); 
int quantity = Integer.parseInt(quantityField.getText()); 

StockItem stockItemUsingSecondConstructor = new StockItem(id, name, desc, price, quantity); 

這就是所謂的超載。 :)

P.S:使用變量使其更清楚。 :)

相關問題