【问题标题】:Resolve "Constructor call must be the first statement in a constructor" java [duplicate]解决“构造函数调用必须是构造函数中的第一条语句”java [重复]
【发布时间】:2020-07-12 00:23:52
【问题描述】:

我有一个类扩展了 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


    【解决方案1】:

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

    如果需要,您可以将列表构建代码提取到单独的静态方法中 - 但在这种情况下,您实际上并不想要一个列表 - 您只需要一个数组,因为超类 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 为空时尝试调用 _temp.add(...)

    如果你真的想要/需要一个辅助方法,这里有一个例子:

    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&lt;T&gt; 有多种流畅的方法 - 这实际上只是为了展示如何调用静态方法 以便为超类提供参数构造函数。

    【讨论】:

      【解决方案2】:

      Triangle 类需要在第一行的构造函数中调用 super()。

          public Triangle(Point3D point3d, Point3D point3d2, Point3D point3d3){
              super(point3d, point3d2, point3d3);
          }
      

      【讨论】:

        猜你喜欢
        • 2013-12-10
        • 2012-12-13
        • 1970-01-01
        • 2017-01-01
        • 2016-11-26
        • 2011-03-24
        • 2015-07-02
        • 2014-10-02
        • 1970-01-01
        相关资源
        最近更新 更多