在Java中所有的类都是Object的子类。
在Object类中有一个clone方法定义如下:
protected native Object clone() throws CloneNotSupportedException;
该方法的修饰符为protected,表示该方法可以在子类中调用
然后结果是调用不了
网上有回答是需要实现Cloneable接口,但即使实现了,也调用不到。
不实现Cloneable接口,只是报CloneNotSupportedException异常。
只能重写clone方法,并且使用super.clone()
疑惑这是为什么呢?
The Cloneable interface is just a flag, it is empty inside.
The clone method of Object is a local method, which is more efficient.
Several conditions for using the clone method
2) In order to obtain a copy of the object, we can use the clone method of the Object class.
3) Override the accumulated clone method in the derived class and declare it as public.
4) In the clone method of the derived class, call super.clone().
For more details, you can refer to
http://www.cnblogs.com/gw811/...
You can call:
clone() is a protected scope. After inheriting the Cloneable interface, you need to override the method, and then call the clone() method of the parent class in the method. At the same time, the default clone is only a shallow clone of the reference object. Let me give you a piece of code to run and try it yourself:
A inherits the cloneable interface and holds a reference to B.
Implement the interface Cloneable and override the clone() method.
I was very confused when I first saw it. I tried it and found that the clone method in the object was directly called.
The code is as follows:
public class CommonTest implements Cloneable{
}