Why is overriding necessary for the clone() method in the class if we are calling the clone() on the instance of the class in some other class?

69 views Asked by At
class Cat {

    int j;

    Cat(int j) {
        this.j = j;
    }
}
class Dog implements Cloneable {

    int i;
    Cat c;

    Dog(Cat c, int i) {
        this.c = c;
        this.i = i;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class ShallowCloneDemo {

    public static void main(String[] args) throws Exception {
        Cat c = new Cat(20);
        Dog d1 = new Dog(c, 10);
        System.out.println(d1.i + " ... " + d1.c.j);

        Dog d2 = (Dog) ((Object) d1).clone();
        d2.i = 888;
        d2.c.j = 999;
        System.out.println(d1.i + " ... " + d2.c.j);
    }
}

In the above program I am calling the clone() method on d1 object inside the ShallowCloneDemo class, so why can't I call the clone() of the Object class(superclass) without overriding clone() in the Dog class?

When I tried calling the clone() from the same Dog class rather than calling it from other class then it worked without any error:

class Cat {

    int j;

    Cat(int j) {
        this.j = j;
    }
}
class Dog implements Cloneable {

    int i;
    Cat c;

    Dog(Cat c, int i) {
        this.c = c;
        this.i = i;
    }

    public static void main(String[] args) throws Exception {
        Cat c = new Cat(20);
        Dog d1 = new Dog(c, 10);
        System.out.println(d1.i + " ... " + d1.c.j);

        Dog d2 = (Dog) d1.clone();
        d2.i = 888;
        d2.c.j = 999;
        System.out.println(d1.i + " ... " + d2.c.j);
    }
}

However, when I tried removing the override of clone() inside the Dog class and called the clone() method from the ShallowCloneDemo class on the d1 object:

class Cat {

    int j;

    Cat(int j) {
        this.j = j;
    }
}
class Dog implements Cloneable {

    int i;
    Cat c;

    Dog(Cat c, int i) {
        this.c = c;
        this.i = i;
    }
}
class ShallowCloneDemo {
    public static void main(String[] args) throws Exception {
        Cat c = new Cat(20);
        Dog d1 = new Dog(c, 10);
        System.out.println(d1.i + " ... " + d1.c.j);

        Dog d2 = (Dog) ((Object) d1).clone();
        d2.i = 888;
        d2.c.j = 999;
        System.out.println(d1.i + " ... " + d2.c.j);
    }
}

then I was having the following compilation issue:

error: clone() has protected access in Object Dog d2 = (Dog)d1.clone();

I am confused as per the definition of the protected access modifier I should be able to call the protected method from anywhere of the same package. I am writing this program on Notepad of Windows and not providing any declaration for the package and also I am saving all these programs in the same folder.

0

There are 0 answers