Is it possible in Java to implement something similar to Object.clone() ?
- by devoured elysium
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?