如下面的示例所示,类Player
是java.lang.Object
的子类,并实现了接口Cloneable
。
public class Player implements Cloneable{
public String name;
public int age;
/**
* I know I should not throw an exception in this method.
* @return the cloned player
* @throws CloneNotSupportedException when the method is not supported.
*/
@Override
public Player clone() throws CloneNotSupportedException {
return (Player) super.clone();
}
@Override
public String toString() {
return name + ": " + age;
}
}
我很好奇Java如何实现对象的克隆过程,但是由于IntelliJ将我带到java.lang.Object
的源代码,而且我只看到以下空白,因此我找不到该方法的实现代码。方法:
protected native Object clone() throws CloneNotSupportedException;
有人可以向我解释这个奇怪的情况吗?是否clone()方法只是神奇地返回具有相同属性的对象?