例如,我有类Human,我想覆盖clone()函数。
clone()的返回类型应该是什么,Object还是Human?我知道返回类型在重写过程中没有任何作用,因为它不在函数的签名中。
例如,在类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();
}
或
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
将使您的生活更轻松(可能为您节省大量的cast),并且没有任何缺点。
我绝对推荐这种方法。