1 java有一个clone的方法。可以理解为克隆。可以理解为复制。如有A,通过clone克隆出来B。B是完全相同的新对象。即A和B是两个独立的对象。如需要克隆。需要类本身具有clone方法。
如:
TestMain2 test2=new TestMain2();
TestMain2 test2_1;
test2_1=test2.clone();//这就是克隆函数clone。
TestMain2:具有clone方法:通过super.clone()来实现。返回的object类型。强制转化即可
public TestMain2 clone(){
try {
return (TestMain2)super.clone();//通过super.clone()来克隆。强制转化为TestMain2即可
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
2 需要实现clone方法。那该类本身就需要实现Cloneable接口。
如:
public class TestMain2 implements Cloneable//实现Cloneable接口
{
public TestMain2 clone(){
try {
return (TestMain2)super.clone();//通过super.clone()来克隆。
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
综述:类克隆,需要类中具有clone方法。而需要有clone方法,则需要实现Cloneable接口。
clone方法中通过super.clone()来实现克隆。
完整的例子:
public class TestMain1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestMain2 test2=new TestMain2();
test2.setAaa("ddd");
TestMain2 test2_1;
test2_1=test2.clone();
System.out.println(test2+"/"+test2.getAaa()+"-----");
System.out.println(test2_1+"/"+test2_1.getAaa()+"---");
}
}
public class TestMain2 implements Cloneable
{
private String aaa="";
public String getAaa() {
return aaa;
}
public void setAaa(String aaa) {
this.aaa = aaa;
}
public TestMain2 clone(){
try {
return (TestMain2)super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}