Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Object.clone() in Java

Tags:

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 it works. We're given 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 N extends Object, how does the super.clone() return an instance of N? super.clone() is actually Object.clone() which returns a reference to an object of class Object. Why are we then able to cast it to N? N has a member num that is not in the class Object. How does the default behavior actually manage to automatically clone this variable (since it has no record of it in class Object)?

Also, the same goes for M. In M.clone() we're casting an object from class N (returned by super.clone()) to an object of class M. I know that all of this is valid, yet I do not understand why.

like image 954
PerakR Avatar asked Aug 26 '26 14:08

PerakR


1 Answers

Object#clone is a native method that makes a low-level binary copy of your object, thus producing another instance of the same class. Therefore it is safe to downcast.

Note that this is the only way to have a polymorphic cloning method.

like image 162
Marko Topolnik Avatar answered Aug 28 '26 04:08

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!