为什么无论是浅拷贝或深copy.Can't我们写的任何方法(方法名称)需要为同样的目的
问题描述:
我真不明白,使用重载的clone()的,在克隆的压倒一切的()我们可以编写任何方法名称,并且可以达到目的。另外,我们不使用父对象(Object)引用来调用克隆方法。那么请使用重写请求解释。为什么无论是浅拷贝或深copy.Can't我们写的任何方法(方法名称)需要为同样的目的
浅复制
class Person implements Cloneable {
private String name;
protected Object copy() {//method name is copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
public void setName(String name) {
this.name = name;
}
}
public class TestClone {
public static void main(String[] args) {
Person ob1 = new Person();
ob1.setName("Bibhu");
Person ob2 = (Person) ob1.copy();
System.out.println(ob1.getClass() == ob2.getClass());//true
}
}
深复制
import java.util.ArrayList;
import java.util.List;
class Company {
private String name;
private List<String> empList = new ArrayList<>();
public Company(String name, List<String> empList) {
this.name = name;
this.empList = empList;
}
public String getName() {
return name;
}
public List<String> getEmpList() {
return empList;
}
public Object copy() {
List<String> tempList = new ArrayList<>();
for (String s : this.empList) {
tempList.add(s);
}
String cName = this.name;
return new Company(cName, tempList);
}
}
public class TestDeepClone {
public static void main(String[] args) {
List<String> empList = new ArrayList<>();
empList.add("Bibhu");
empList.add("Raj");
empList.add("John");
Company c1 = new Company("ABC Company", empList);
Company c2 = (Company) c1.copy();
System.out.println(c1.getClass() == c2.getClass());//true
System.out.println(c1.getEmpList() == c2.getEmpList());//false
}
}
答
它只是约定。即使是JavaDoc sais:
按照惯例,实现此接口的类应该用公共方法覆盖 Object.clone(它受保护)。有关覆盖此方法的详细信息,请参阅 Object.clone()。