Understanding Object.clone () in Java

I know that using this cloning mechanism is not a good idea (since it is “broken”, as some authors suggest), although I need help understanding how this works. We are assigned the following class hierarchy:

class N implements Cloneable{
    protected int num;
    public N clone() throws CloneNotSupportedException{
        return (N)super.clone();
    }
}

class M extends N{
    protected String str;
    public M clone() throws CloneNotSupportedException{
        M obj = (M)super.clone();
        obj.setString(new String(this.str));
        return obj;
    }
    void setString(String str){
        this.str = str;
    }
}

Since Nextends Object, how does an super.clone()instance return N? super.clone()actually Object.clone()which returns a reference to the class object Object. Why can we pass it on N? Nhas a member numwho is not in the classroom Object. How does the default behavior really allow you to automatically clone this variable (since it does not have an entry in the class Object)?

, M. M.clone() N ( super.clone()) M. , , , .

+3
4

Object#clone - , , . .

, .

+6

, Object.clone() :

protected native Object clone() throws CloneNotSupportedException;

JVM , , . , .

+2
  • N extends Object, super.clone() N?
  • super.clone() Object.clone(), Object. N?
  • N num, . ( Object)?

:

  • N, . , N. Object - . N.toString(), toString, JVM N .
  • , , N.
  • : Java?
0

XStream , :

public static <T> T cloneObject(
    T object) {
    XStream xstream = new XStream();
    return (T) xstream.fromXML(xstream.toXML(object));
  }
0

Source: https://habr.com/ru/post/1663799/


All Articles