在复制ctor,Java中调用super()之前进行空检查

时间:2014-05-01 21:51:50

标签: java nullpointerexception null copy-constructor

我有一个实现接口形状的基类Polygon,以及另一个扩展Polygon的类Triangle,现在在Triangle复制构造函数中我需要检查给定的另一个三角形是不是空指针但是我不能这样做因为我必须使用super()才能初始化我的点数组。

这是我的代码: 多边形 - 抽象类:

public abstract class Polygon implements Shape {
private Point[] points;

/**
 * Build a Polygon that hold a set of Points.
 * 
 * @param points
 *            (Point[])
 */
public Polygon(Point[] points) {
    this.points = points;
}

三角形子类:

public class Triangle extends Polygon {

/**
 * Constructor.
 * Build a Triangle from 3 Point's.
 * @param p1
 * @param p2
 * @param p3
 */
public Triangle(Point p1, Point p2, Point p3) {
    super(new Point[] { p1, p2, p3 });
}

/**
 * Copy constructor.
 * @param other
 */
public Triangle(Triangle other) {
    /*
     * *********************************************
     * 
     * Here is where i want to make the null check .
     * 
     * *********************************************
     */
    super(other.getPoints().clone());
}

提前致谢!

1 个答案:

答案 0 :(得分:5)

使用静态辅助方法:

public Triangle(Triangle other) {
    super(clonePoints(other));
}

private static Point[] clonePoints(Triangle other) {
     if (other == null) {
         // ...
     }

     return other.getPoints().clone();
}

另外,我经常做的是创建一个更通用的辅助方法:

public Triangle(Triangle other) {
    super(neverNull(other).getPoints().clone());
}

private static <S extends Shape> S neverNull(S notNull) {
     if (notNull == null) {
         // throw a meaningful exception 
         // or return a default value for S if possible / reasonable
     }

     return notNull;
}