【发布时间】:2014-05-01 21:51:49
【问题描述】:
我有一个实现接口 Shape 的基类 Polygon 和扩展 Polygon 的另一个类 Triangle ,现在在 Triangle 复制构造函数中,我需要检查给定的另一个三角形是否不是空指针,但我不能这样做,因为我必须使用 super() 来初始化我的 points 数组。
这是我的代码: 多边形 - 抽象类:
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());
}
先谢谢了!
【问题讨论】:
-
处理不应为空但为空的参数的推荐方法是抛出 NullPointerException。这就是您的代码将执行的操作。所以你不需要做任何事情。如果您真的想抛出更详细或不同的异常,请参阅 Lukas 的回答。
-
thnks ,我真的很想抛出一个我自己的异常。
标签: java nullpointerexception null copy-constructor