递归构造函数调用?

时间:2021-04-20 14:48:26

标签: java recursion constructor

public class RGBImage {

    private RGBColor[][] _image;

    public RGBImage(RGBColor[][] pixels) {
        _image = new RGBColor[pixels.length][pixels[0].length];
        for (int i = 0; i < _image.length; i++)
            for (int j = 0; j < _image[i].length; j++)
                _image[i][j] = new RGBColor(pixels[i][j]);
    }

    public RGBImage(RGBImage other) {
        this(new RGBImage(other._image));
    }

第二个构造函数应该调用第一个构造函数,但给了我“递归构造函数调用”错误。
我明白错误意味着什么,我只是不明白递归在哪里。第一个构造函数将 RGBColor[][] 作为参数,而 other._image 应该是该类型的数组。我在这里错过了什么?

谢谢。

1 个答案:

答案 0 :(得分:0)

第二个构造函数应该看起来像这样:

public RGBImage(RGBImage other) {
    this(other._image);
}

您的版本创建了另一个实例,该实例又创建了另一个实例,依此类推。 this() 已经在调用另一个构造函数,无需new 一个新实例。

相关问题