我有一项任务需要减少构造函数中的代码,但是当我按照给定示例执行时它不起作用:(
源代码看起来是这样的:
public class Item {
private Product product;
private int stock;
Item(Product product){
this.product=product;
this.stock=0;
}
Item(Product product, int stock){
this.product=product;
this.stock=stock;
}
我试着这样写:
public class Item {
private Product product;
private int stock;
Item(Product product){
this(product, 0);
}
Item(Product product, int stock){
this(product, stock);
}
谁能告诉我哪里出了问题?
最佳答案
第二个构造函数中有一个循环引用,它正在调用自己。试试这个:
// this constructor is correctly defined
public Item(Product product, int stock) {
this.product = product;
this.stock = stock;
}
// this constructor calls the other one
public Item(Product product) {
this(product, 0);
}
关于java - this(<params>) 作为构造函数中的快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33986303/