javaclonecloneable

Does the clone method clone overridden methods?


If I clone an instance of the following class, and overridde a method when instancing, will the clone have the overridden method? I haven't found anything regarding this behavior in https://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html nor https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone() .

public class ToBeCloned implements Cloneable{
    public int returnInt() {
        return 1;
    }
    public void printTest() {
        System.out.println("returnInt():"+returnInt()+"\nToBeCloned Original");
    }
    @Override
    public ToBeCloned clone() throws CloneNotSupportedException {
        return (ToBeCloned) super.clone();
    }
}

Solution

  • If you do something like

    new ToBeCloned() { @Override...}
    

    it is just a short way of creating a subclass and instantiating it. If you clone that instance, you get another instance of the same anonymous subclass, with all the same methods.