首页 > 解决方案 > 解决“构造函数调用必须是构造函数中的第一条语句”java

问题描述

我有一个类扩展了 Java 中的另一个类

我需要构造函数来运行超级 ctor

这是我的基本代码:

public class Polygon implements Geometry {



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

我想从子类中调用它

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

}

我该怎么做,因为我收到错误“构造函数调用必须是构造函数中的第一个语句”,但我需要构建 ctor

谢谢

标签: java

解决方案


super调用始终必须是构造函数主体的第一条语句。你无法改变这一点。

如果需要,您可以将列表构建代码提取到单独的静态方法中 - 但在这种情况下,您实际上并不想要一个列表 - 您只需要一个数组,因为超类Point3D... vertices参数。所以你可以写:

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

请注意,如果您的原始代码已经编译,它仍然会失败,NullPointerException因为您会尝试调用_temp.add(...)when_temp为 null。

如果您真的想要/需要辅助方法,这是一个示例:

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

请注意,List<T>无论如何都有在单个表达式中构造 a 的流畅方法 - 这实际上只是为了展示如何调用静态方法以便为超类构造函数提供参数。


推荐阅读