Recursive constructor invocation?

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

The second constructor is supposed to call the first one, but instead gives me the "Recursive constructor invocation" error.
I understand what the error means, I just don't understand where the recursion is. The first contructor takes RGBColor[][] as a parameter, and other._image is supposed to be an array of that type. What am I missing here?

Thanks.

1 Answers

The second constructor should probably look like this:

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

Your version creates yet another instance which creates yet another instance and so on. this() is already calling the other constructor, no need to new a new instance.

Related