繁体   English   中英

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

[英]Access constructor variables from another constructor in the same class

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());
    }
}

第二个构造函数读取传递给它的文件,并且我已经成功地将这些值存储在vertices数组中,但是如何将第二个构造函数的vertices数组作为参数传递给第一个构造函数,从而使v = vertices

您需要使用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或轻松合并验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM