Home >Java >Javagetting Started >Deep copy and shallow copy of java object copy

Deep copy and shallow copy of java object copy

王林
王林forward
2019-11-25 15:28:282589browse

Deep copy and shallow copy of java object copy

1. To implement object copying, a Cloneable interface must be implemented. If this interface is not implemented, a CloneNotSupportedException will be generated. In fact, this interface does not have a single method, so this type of interface is often called a marker interface.

2. There is a clone() method in Object that implements shallow copy. For member variables of basic data types, shallow copy will directly transfer the value, that is, copy the attribute value to the new object, so basic data types can be shallow copied directly.

For variable data types, such as Date objects, deep copies must be implemented. Of course, the Date class itself implements the clone() method, but the String class, for example, does not implement the clone() method because String objects cannot There is no way to change the character sequence in its life cycle to modify the character sequence in the memory. There is no problem if similar attributes in different objects refer to the same String.

java learning video tutorial: java learning video

Examples are as follows:

public class Main{
	public static void main(String[] args){
	}
}
class Employee implements Cloneable{
	private int id;
	private Date date;
	public Employee(){}
	public Employee(int id){
		this.id=id;
		this.date=new Date();
	}
	@Override
	public Employee clone() throws CloneNotSupportedException{
		Object t=super.clone();//此时的object中的拷贝只是浅拷贝
		Employee clone=(Employee)t;
		clone.date=this.data.clone();//date类实现了深拷贝,直接调用即可
		return clone;
	}
}
class Mannager extends Employee{
	private String name;
	public Mannager(){
		super();
	}
	public Mannager(String name,int id){
		super(id);
		this.name=name;
	}
	@Override
	public Mannager clone(){
		Employee t=super.clone();//先把id date属性复制
		Mannager clone=(Mannager)t;
		clone.name=t.name;//String 对象直接赋值引用
		return clone;
	}
}

More java related article recommendations: java introductory tutorial

The above is the detailed content of Deep copy and shallow copy of java object copy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete