Object 类是JAVA中所有类的父类,
所有的类都继承了该类中的方法
clone()方法:
该方法是将一个对象的拷贝返回。
在Object类中的定义是
protected object clone() throws CloneNotSupportedException{}
但是,在拷贝的过程中会出现所谓的“浅拷贝”和“深拷贝”的问题,所以通常情况下要重写clone()。
当你要拷贝的对象中的属性有一个对象类型时,它所拷贝的只是该对象属性的一个地址而已,
用“==”测试 发现所指的是一个对象,着就是所谓的“浅拷贝”;“深拷贝”就是我们要产生两个完全独立 的对象个体。所以我们要重写clone()方法;
public class testClone implements Cloneable{
private String name;
private int age;
public testClone(String name,int age){
this.name = name;
this.age = age;
}
protected Object clone()throws CloneNotSupportedException{
testClone tc3 = new testClone(new String(this.name),this.age);
return tc3;
}
public static void main(String[] args){
testClone tc1 = new testClone("shishao",20);
testClone tc2 = null;
try{
tc2 = (testClone)tc1.clone();
}catch(CloneNotSupportedException cns){cns.printStackTrace();}
System.out.println(tc1.name+tc1.age);
System.out.println(tc2.name+tc2.age);
if(tc1.name==tc2.name){
System.out.println("the two objects has the same address");
}else{
System.out.println("the two objects has different address");
}
tc1.name="liu";
if(tc1.name==tc2.name){
System.out.println("the two objects has the same address");
}else{
System.out.println("the two objects has different address");
}
System.out.println(tc1.name+tc1.age);
System.out.println(tc2.name+tc2.age);
}
}
以上代码就是一个小的测试,
在这段代码中,出现的String 类型的对象。该类型的对象具有对象池的特性,
所谓的“对象池”就是在java语言中为了避免频繁的创建对象而消耗系统的资源,就引入了“对象池”的这个机制
当一个对象使用完后,并不立即的被销毁,当下次要创建给类型的对象是就要到“对象池”看是否有了这样的对象,如果有了就直接的拿来用,如果没有就再创建一个新的对象,
所以
protected Object clone()throws CloneNotSupportedException{
testClone tc3 = new testClone(new String(this.name),this.age);
return tc3;
}
中new String(this.name)是必须的 否则测试是不会成功的,因为存在“对象池”的机制