Is it possible in Java to implement something similar to Object.clone() ?

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-03-25T17:56:15Z Indexed on 2010/03/25 18:23 UTC
Read the original article Hit count: 112

Filed under:

The Object.clone() method in Java is pretty special, as instead of returning a copy of the object that is to be cloned with the Object type, it returns the correct Object type. This can be better described with the following code:

class A extends Object {
    public A clone() {
        return super.clone(); //although Object.clone() is from the Object class
                              //this super.clone() will return an A object!
    }
}

class B extends A {
}

public static void main(String[] args) {
    B = new B();
    B.clone();//here, although we haven't defined a clone() method, the cloned
              //object return is of type B!
}

So, could anyone explain if possible if is there anyway to replicate what happens inside Object.clone()'s method?

© Stack Overflow or respective owner

Related posts about java