java - this(<params>) 作为构造函数中的快捷方式?

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

谁能告诉我哪里出了问题?

最佳答案

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

// 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/

相关文章:

java - 如何计算 map 跨度/缩放以在视口(viewport)中包含一组 GeoPoints?

java - Facelet 模板呈现两个 HTML 标签

c++ - 构造函数上没有匹配的函数调用

jQuery 选择器上下文在 $().find 中不起作用

c++ - 对两个构造函数使用 'this' 指针

javascript - 理解 .bind() 与参数的关系

java - Java 中的花式循环

java - 将 'null' 类型转换为 JAVA 中的任何引用类型有什么用?

c++ - 在 C++ 中总是调用空构造函数吗?

objective-c - 使用自定义方法将自定义对象添加到数组 Swift 问题