clone() method in Java

前端 未结 5 994
再見小時候
再見小時候 2021-02-14 22:14

as I understood, the method clone() gives us the ability to copy object (no refernce) in Java. But I also read, that the copy is shallow. So what the point? Which a

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 23:05

    to clone in depth you have to implement Cloneable and override clone()

    public class MyClass implements Cloneable {
    
    private Object attr = new Object();
    
    @Override
    public Object clone() throws CloneNotSupportedException {
        MyClass clone = (MyClass)super.clone();
        clone.attr = new Object();
        return clone;
    }
    
    @Override
    public String toString() {
        return super.toString()+", attr=" + attr;
    }
    
    public static void main(String[] args) throws Exception {
        MyClass x = new MyClass();
        System.out.println("X="+x);
        MyClass y = (MyClass)x.clone();
        System.out.println("Y="+y);
    }
    

    }

提交回复
热议问题