java - 解决“构造函数调用必须是构造函数中的第一条语句”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
谢谢
解决方案
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 的流畅方法 - 这实际上只是为了展示如何调用静态方法以便为超类构造函数提供参数。
推荐阅读
- c# - Firesharp:执行请求时发生错误。路径:0/,方法:PUT
- php - 将对象对象转换为对象数组(PHP,Laravel)
- java - 每次使用新值启动时如何重置倒数计时器?
- c# - JsonConvert - 强制 MissingMember 为空
- kubernetes - 在 2 节点裸机集群上设置 Rancher Hello World
- javascript - 如何让不同的元素同时响应 - 按下多个按钮同时点亮多个框
- ios - 使用 CoreData 和数组填充表视图部分
- java - zeroDateTimeBehavior=convertToNull 在使用休眠的 jdbc url 中不起作用
- html - woocommerce 电子邮件中的 TM 符号图像而不是 unicode 特殊字符
- excel - 比较产生意外结果的字符串