Solutions to problems encountered when using the clone() method (JAVA)

We usually encounter 4 problems in a row when using this method in custom types.

The basic code is as follows:

class A {
    int[] a = {1,2,3};
}

public class Test {
    public static void main(String[] args) {
        
    }
}

First:

The reason for the error when we call it directly is that the clone method in the Object class is protected and needs to be rewritten.

the second:

The reason why we report an error after rewriting is that the clone method may throw a CloneNotSupportedException exception, and it is a checked exception so we need to handle it.

The third:

After we handle the above CloneNotSupportedException exception, there will be a new exception. The reason is because the Object type returned by clone needs to be forced.

the fourth:

After all the above problems are solved, it seems to be fine at first glance, but when we run it, an error will be reported again. Says this class does not support cloning.

The solution at this time is to let the cloned class implement the Cloneable interface, and you're done.

Note: The clone() method defaults to shallow copy.

Guess you like

Origin blog.csdn.net/2302_76339343/article/details/133818982