Object cloning Study

Object cloning

  • It refers to a cloning target object assignment

clone () method

protected Object clone() throws CloneNotSupportedException
  • Creates and returns a copy of a copy of this object

CloneNotSupportedException abnormal

  • Cloneable interface

    This interface can not see abstract method for marking the interface , showing a method of operating capability.

  • Achieve cloning operation

class Book implements Cloneable { // 实现 Cloneable接口,对象可以被克隆
    private String title ; 
    private double price ; 
    
    public Book(String title , double price) {
        this.title = title ;
        this.price = price ; 
    }
    
    @Override
        public String toString() {
            return "title:" + this.title + "\t price:" + this.price ;
        }
    @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }// 覆写 clone方法,调用父类的clone()方法,可以实现对象克隆
}

public class TestDemo {
    public static void main(String [] args) throws CloneNotSupportedException {
        Book book_A = new Book("Java",11.1) ; 
        Book book_B = (Book) book_A.clone() ; 
        // 克隆操作 完成
    }
}

Theoretical value higher than the actual value of the object cloning

  • Key:

The above code, referred to the marker interface, the key to this concept is very important, like a marker interface card, like a password, only to get (to achieve) marker interface (password card) before they can enter some specific places (execution)

clone method override the parent class in the class Book, changing the type of the method, and to achieve indirect call clone () method call permission (characteristic) of the present method through the outer class class; thus ignoring the access control protected. Here is the equivalent of the Book middle class as excessive password door, using the Book class calling outside the class but can not be called the Book class can be called using the class.

Guess you like

Origin www.cnblogs.com/wangyuyang1016/p/11094471.html