构造函数名称相同,但不同的签名不运行
问题描述:
我有那些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构造函数后也尝试过。
答
在您的toString()
方法StockItem
中,您还必须包括quantity
。例如:
public String toString() {
return id + ", " + name + ", " + description + ", " + price + ", " + quantity;
}
这样,当你做System.out.println(item2);
,该toString()
将包括在结果中quantity
被调用。
答
对于一个你没有使用你的问题中显示的构造函数。您正在创建一个新对象,然后使用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()方法输出中。
答
您使用它的构造函数不在您在此处显示的构造函数中。你确定你可以在没有参数的情况下创建新的构造函数吗?如果我没有错,你应该像这样使用它们。如果你想使用第一构造:
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:使用变量使其更清楚。 :)
你甚至不*调用构造函数,你可以调用setter。你的二传手是否坏了? – 2014-10-28 12:55:56