Search code examples
javaclonecloneable

java: clone method violation


Code behind:

class A implements Cloneable
{
    int i, j;

    A(int i, int j)
    {
        this.i = i;
        this.j = j;
    }

    A()
    {
    }
}

class B extends A
{
    int l, m;

    B()
    {
    }

    B(int l, int m)
    {
        this.l = l;
        this.m = m;

    }

    public static void main(String l[])
    {
        A obj = new A(1, 2);
        B obj1 = (B) obj.clone(); // ERROR
    }
}

I know that I am violating the meaning of clone as I am trying to assign the fields of one object to a completely different object. But its the error statement that is confusing me.

Statement: "error: clone() has protected access in Object"

Extending A should make clone() available to B also ? If that is, so values of i and j should be copied to l and m also ? Is this possible ?


Solution

  • clone() is protected method and to make accessible in sub-classes, override it with public access.

    class A implements Cloneable{
        .....
        @Override
        public Object clone() throws CloneNotSupportedException{
          return super.clone();
        }
    }