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.