MENU

clone

December 7, 2021 • 编程,JAVA阅读设置

clone

克隆就是在内存里边赋值一个实例对象。但是Object 的克隆方法只能 浅拷贝。同时必须实现Cloneable 接口

public class Dog implements Cloneable {
    public Dog newDog(){ 
        try { 
            return (Dog)this.clone();  
        } catch (CloneNotSupportedException e) { 
            e.printStackTrace();         
            return null;
        }
    }

public static void main(String[] args) { 
        Dog dog = new Dog();
        Dog newDog = dog.newDog();  
        System.out.println(dog == newDog);
    }
}
浅拷贝不会拷贝引用类型
Last Modified: February 5, 2023