0

I have a class that extends another class in Java

I need the constructor to run the super ctor

this is my base code:

public class Polygon implements Geometry {



    public Polygon(Point3D... vertices) {
       ......
        }
    }

and I want to call it from sub class

public class Triangle extends Polygon {

    //ctor
    public Triangle(Point3D point3d, Point3D point3d2, Point3D point3d3){
        List<Point3D> _temp = null;
        _temp.add(point3d);
        _temp.add(point3d2);
        _temp.add(point3d3);
        super(_temp);
    }

}

How can I do it because I get the error "Constructor call must be the first statement in a constructor", but I need to build the ctor

Thanks

24sharon
  • 1,859
  • 7
  • 40
  • 65

2 Answers2

7

The super call always has to be the first statement of the constructor body. You can't change that.

You could extract the list-building code to a separate static method if you needed to - but in this case, you don't actually want a list anyway - you just want an array, because of the superclass Point3D... vertices parameter. So you can write:

public Triangle(Point3D point3d, Point3D point3d2, Point3D point3d3) {
    // The vertices parameter is a varargs parameter, so the compiler
    // will construct the array automatically.
    super(point3d, point3d2, point3d3);
}

Note that if your original code had compiled, it would still have failed with a NullPointerException because you'd be trying to call _temp.add(...) when _temp was null.

Here's an example if you genuinely wanted/needed a helper method:

public class Polygon implements Geometry{
    public Polygon(List<Point3D> vertices) {
        ...
    }
}

public class Triangle extends Polygon {
    public Triangle(Point3D point3d, Point3D point3d2, Point3D point3d3) {
        // The vertices parameter is a varargs parameter, so the compiler
        // will construct the array automatically.
        super(createList(point3d, point3d2, point3d3));
    }

    private static List<Point3D> createList(Point3D point3d, Point3D point3d2, Point3D point3d3) {
        List<Point3D> ret = new ArrayList<>();
        ret.add(point3d);
        ret.add(point3d2);
        ret.add(point3d3);
        return ret;
    }
}

Note that there are fluent ways of constructing a List<T> in a single expression anyway - this is really just to show how a static method can be called in order to provide an argument to the superclass constructor.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

The class Triangle needs to call super() from the constructor in the first line.

    public Triangle(Point3D point3d, Point3D point3d2, Point3D point3d3){
        super(point3d, point3d2, point3d3);
    }
Jason
  • 5,154
  • 2
  • 12
  • 22