从同一个类中的另一个构造函数访问构造函数变量

时间:2013-11-20 09:54:40

标签: java constructor

public GObject(Point3D[] v, Face[] f){
    vertex = v;
    face = f;
}

public GObject(String fileName){
    try{
           ...//read contents of file and store in an array
           Point3D[] vertices = new Point3D[numOfVertices];

    } catch(Exception e){
           System.out.println("Can't read file " + e.getMessage());
    }
}

第二个构造函数读取传递给它的文件,并且我已成功地将这些值存储在顶点数组中,但是如何将顶点数组从第二个构造函数传递给第一个作为参数的第一个,以便{{1 }}?

1 个答案:

答案 0 :(得分:2)

您需要使用this -

public GObject(String fileName){
    this(new Point3D[numOfVertices], new Face[5]); // `5` is just for example.

    try{
       ...//read contents of file and store in an array
       Point3D[] vertices = new Point3D[numOfVertices];

    } catch(Exception e){
       System.out.println("Can't read file " + e.getMessage());
    }
}

请注意,如果使用此方法,则对this的调用必须是第二个构造函数的第一个语句。如果你很难理解这个限制,那么我建议你做这样的事情 -

public GObject(Point3D[] v, Face[] f){
    setV(v);
    face = f;
}

public GObject(String fileName){
    try{
       ...//read contents of file and store in an array
       setV(new Point3D[numOfVertices]);
    } catch(Exception e){
       System.out.println("Can't read file " + e.getMessage());
    }
}

private void setV(Point3D[] v) {
    vertex = v;
}

我认为第二种方法更好,因为它不会强迫你构造一个Face数组只是为了调用另一个构造函数。您也可以稍后更改setting logic或轻松合并验证。