【发布时间】:2016-12-03 23:27:42
【问题描述】:
假设我有一个具有多个构造函数的类,其中一个是复制构造函数(用于复制对象):
public class Rectangle {
int width, height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public Rectangle(Rectangle source) {
this(source.width, source.height);
}
}
有什么方法可以检查复制构造函数中的source 是否为null,如果是则抛出IllegalArgumentException?因为另一个构造函数调用 必须 是我构造函数中的第一个语句。
【问题讨论】:
-
为什么其他构造函数调用必须是复制构造函数中的第一个语句?
-
因为这就是 Java 想要的。
-
@Janno:因为这就是 Java 的工作方式。你不能在另一个语句之后使用
this(...)。 -
当
null被传递时,我会将其保留为 NPE。
标签: java constructor copy-constructor