2014-10-28 84 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:使用变量使其更清楚。 :)

相关问题