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());
}
}
请注意,如果使用这种方法,则tothis
必须是第二个构造函数的第一条语句。如果您很难遵守这个限制,那么我建议您做这样的事情-
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
或轻松合并验证。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句