例如,我有类人,我想覆盖克隆()函数。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