例如,我有類人,我想覆蓋克隆()函數。clone()的返回類型應該是什麼?
clone(),Object或Human的返回類型應該是什麼?我知道返回類型在重寫過程中沒有任何作用,因爲它不在函數的簽名中。
例如,在類人應該我有
public Object clone() throws CloneNotSupportedException {
Human h = (Human)super.clone();
h.age = age;
h.name = name;
return h;
}
,然後在主
public static void main() throws CloneNotSupportedException {
Human h = new Human("Slavco", 49);
Human z = (Human)h.clone();
}
OR
public Human clone() throws CloneNotSupportedException {
Human h = (Human)super.clone();
h.age = age;
h.name = name;
return h;
}
,並在主
public static void main() throws CloneNotSupportedException {
Human h = new Human("Slavco", 49);
Human z = h.clone();
}
是什麼原因*不*返回'Human'?是的,返回類型*確實有重寫規則:它應該是原始返回類型的子類型。 – Elazar
使用第二種方法。 –
它們都重寫默認的Object構造函數,但在方法定義中返回Human更清晰,它還允許您在人類對象上調用clone並且不必投射。 – greedybuddha