这个(<params>)作为构造函数中的快捷方式?

时间:2015-11-29 18:23:36

标签: java constructor this

我得到了一个我需要在构造函数中减少代码的任务,但是当我在给定示例中执行时它不起作用:(

源代码看起来如此:

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);
        }

有人可以告诉我,有什么问题吗?

2 个答案:

答案 0 :(得分:3)

在第二个构造函数中有一个循环引用,它正在调用它自己。试试这个:

// 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);
}

答案 1 :(得分:0)

你的第二个构造函数试图调用自己,这没有任何意义。

如果你的类有一个具有相同参数的构造函数的超类,你可以写:

    Item(Product product, int stock){
        super(product,stock);
    }

因为它没有,你应该只在第二个构造函数中分配实例的成员:

    Item(Product product, int stock){
        this.product = product;
        this.stock = stock;
    }