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 the clone, as I am trying to assign the fields of one object to a completely different object. But this is a mistake that confuses me.

Statement: "error: clone () has secure access in the object"

Should extension A also make clone() available to B? If so, then the values ​​i and j should also be copied to l and m? Is it possible?

+6
source share
2 answers

clone () is a protected method and made available in subclasses, override it using public access.

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

From Javadoc Cloneable

By convention, classes that implement this interface must override Object.clone (which is protected) with a public method. See Object.clone () for details on overriding this method.

Please note that this interface does not contain a cloning method. Therefore, it is not possible to clone an object only because it implements this interface. Even if the clone method is activated reflectively, there is no guarantee that it will succeed.

Clone is one of the earliest projects in java and has flaws

About access - When a method is protected, it can only be accessed by the class itself, subclasses of the class, or classes in the same package as the class .

Thus, it is available in classes A and B , the way you do this is only possible if you are in the same package, which turns out to be java.lang

You can provide some method like this inside A

 public A copy() throws CloneNotSupportedException { return (A) clone(); } 

Correct implementation

  @Override public Object clone() throws CloneNotSupportedException { return super.clone(); }; 

Also remember that the parent is not a type of child, so dropping from A to B will not work. A child is a type of parent, so work from B to A will work.

+3
source

Source: https://habr.com/ru/post/925985/


All Articles