Ballamory
Ballamory

Reputation: 151

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

The second constructor reads the file that was passed to it and I've stored those values successfully in the vertices array but how can I pass the vertices array from the second constructor to the first one as a parameter so that v = vertices?

Upvotes: 1

Views: 85

Answers (1)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

You need to use 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());
    }
}

Do note that if you use this approach, then call to this must be the very first statement of your second constructor. If this restriction is hard to follow for you, then I suggest you do something like 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;
}

I think the second approach is better, as it doesn't force you to construct a Face array just for the sake of calling the another constructor. Also you can later change the setting logic or incorporate validation easily.

Upvotes: 2

Related Questions