clone in java

library class

1. The cloned class needs to implement the Cloneable interface and override the clone method of Object.

public class TuShuGuan implements Cloneable{
	private String shuming;
	private String time;
	public TuShuGuan(String shuming, String time) {
		super();
		this.shuming = shuming;
		this.time = time;
	}
	public void setShuming (String shuming) {
		this.shuming = shuming;
	}
	public void setTime(String time) {
		this.time = time;
	}
    public String getShuming() {
		return shuming;
	}
	public String getTime() {
		return time;
	}
	public Object clone() throws CloneNotSupportedException {  
        return super.clone();  
    }  
}

main function

The main function needs to throw CloneNotSupportedException

/**
 *clone in Java
 * @author Administrator
 *
 */
public class CloneTest {
	public static void main(String[] args)throws CloneNotSupportedException{
		TuShuGuan t = new TuShuGuan("java","2017年");
		System.out.println(t.getShuming()+"---"+t.getTime());
		Object obj = t.clone();
		TuShuGuan t2 = (TuShuGuan)obj;
		System.out.println(t2.getShuming()+"---"+t2.getTime());
		TuShuGuan t3 = t;
		t3.setShuming("C++");
		t3.setTime("2018年");
		System.out.println(t3.getShuming()+"---"+t3.getTime());
		System.out.println(t2.getShuming()+"---"+t2.getTime());
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325936187&siteId=291194637