Java learning summary: 34 (object cloning)

Object cloning

Object cloning is a copy operation on an object. In the Object class, there is a clone () method for the object cloning operation. The method is as follows:

protected Object clone() throws CloneNotSupportedException;

We have noticed:
1. This method uses protected access rights, so that when the object is generated from different packages, the clone () method in the Object class cannot be called, so it is necessary to override the clone () method in the subclass to complete normally. Clone operation;
2. A "CloneNotSupportedException" (unsupported clone exception) is thrown on the clone () method, because not all objects of all classes can be cloned, so in order to distinguish which objects can be cloned in Java, Provides a Cloneable interface specifically, the class to clone the object must implement the Cloneable interface.

Note: The Cloneable interface does not have any methods, this interface belongs to the identification interface .
Regarding the identification interface: The identification interface is an interface without any methods and attributes. The identification interface does not have any semantic requirements for the class that implements it, it only indicates that the class that implements it belongs to a specific type.

Example: Implement clone operation

package Project.Study.ObjectCloning;

class Book implements Cloneable{	//此类对象可以被克隆
    private String title;
    private double price;
    public Book(String title,double price){
        this.title=title;
        this.price=price;
    }

    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public String toString(){
        return "书名:"+this.title+",价格:"+this.price;
    }
    //由于此类需要对象克隆操作,所以才需要进行方法的覆写
    @Override
    public Object clone() throws CloneNotSupportedException{
        return super.clone();	//调用父类的克隆方法
    }
}
public class Test1 {
    public static void main(String[]args) throws Exception {
        Book book1=new Book("Java",79);	//实例化对象
        Book book2=(Book)book1.clone();	//克隆对象,开辟新的堆内存空间
        book2.setTitle("C++");			//修改克隆对象属性,不影响其他对象
        System.out.println(book1);
        System.out.println(book2);
    }
}
//结果:
//书名:Java,价格:79.0
//书名:C++,价格:79.0(克隆对象)

The above program uses the content of the book1 object to clone a new Book class object book2. Since these two objects occupy different heap memory space, they will not affect each other.

49 original articles published · Liked 25 · Visits 1512

Guess you like

Origin blog.csdn.net/weixin_45784666/article/details/105225366