其他分享
首页 > 其他分享> > Cloneable的使用

Cloneable的使用

作者:互联网

Cloneable的使用

public class DeepCopy implements Cloneable{
    private int id;
    private String name;
    private String school;

    @Override
    protected Object clone()  {
        DeepCopy deepCopy = null;
        try {
            Random r = new Random(1);
            deepCopy = (DeepCopy)super.clone();
            deepCopy.id = r.nextInt(100);
            deepCopy.name = this.name;
            deepCopy.school = this.school;
        }  catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return deepCopy;
    }
}

public static void main(String[] args) {
	// write your code here
	DeepCopy deepCopy = new DeepCopy();
	deepCopy.setId(1);
	deepCopy.setName("zs");
	deepCopy.setSchool("一中");
	Object clone = deepCopy.clone();
	System.out.println(deepCopy.toString());
	System.out.println(clone.toString());
}
//输出结果
DeepCopy{id=1, name='zs', school='一中'}
DeepCopy{id=85, name='zs', school='一中'}

标签:school,name,clone,使用,Cloneable,deepCopy,DeepCopy
来源: https://www.cnblogs.com/fooller/p/14116432.html