Friday, June 28, 2019

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 ?


Answer



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();
}
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...