为什么构造函数链接会导致堆栈溢出(java)

问题描述 投票:0回答:1
So I have the code below but it caused java.lang.StackOverFlowError.
I guess maybe creating an new object inside the second constructor may 
have caused an infinite loop or something. But I don't fully understand
why this happened. Could someone explain it to me? I'd appreciate it!

所以我有下面的代码,但它导致java.lang.StackOverFlowError。 我想也许在第二个构造函数中创建一个新对象 造成了无限循环或其他原因。但是我不完全了解 为什么会这样。有人可以向我解释吗?我将不胜感激!

```private double x;
private double y;
private double z;
private double[] elements;
/**
 * Creates a 3D vector from an array
 * @param v array containing 3 components of the desired vector 
 */
public Vector3(double[] v) {
    this(v[0], v[1], v[2]);
}

/**
 * Creates a 3D vector from 3 numeric scalar components
 * @param x x coordinate
 * @param y y coordinate
 * @param z z coordinate
 */
public Vector3(double x, double y, double z) {
    this(new Vector3(x, y, z));
}

/**
 * Clones an existing vector
 * @param old an existing Vector3 object 
 */enter code here
public Vector3(Vector3 old) {
    x = old.x;
    y = old.y;
    z = old.z;
    elements = new double[3];
    elements[0] = x;
    elements[1] = y;
    elements[2] = z;
}```
java constructor
1个回答
0
投票
public Vector3(double x, double y, double z) {
    this(new Vector3(x, y, z));
}

我不确定您要做什么,但似乎您是在本身调用Vector3构造函数。这导致了无限循环。

© www.soinside.com 2019 - 2024. All rights reserved.