比方說,我有多個構造一類,其中之一是一個拷貝構造函數(複製對象):Java的空參數時鏈構造
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
?因爲其他構造函數調用已將作爲我構造函數中的第一個語句。
爲什麼其他構造函數調用必須是複製構造函數中的第一條語句? – Janno
因爲這就是Java所需要的。 – kalsowerus
@Janno:因爲這就是Java的工作原理。在另一個陳述之後不能使用this(...)。 –