为什么必须对克隆对象进行类型转换?
Why does cloned object have to be typecasted?
为什么 Java 中的克隆对象必须进行类型转换?例如:
Vector<Integer> vec = new Vector<Integer>();
Vector<Integer> clone = (Vector)vec.clone();
为什么 clone()
return Object
引用,而不是适当的 class 的克隆?
因为clone()
方法源自对象class本身。
/**
* Answers a new instance of the same class as the receiver,
* whose slots have been filled in with the values in the
* slots of the receiver.
* <p>
* Classes which wish to support cloning must specify that
* they implement the Cloneable interface, since the native
* implementation checks for this.
*
* @return Object
* a shallow copy of this object.
* @exception CloneNotSupportedException
* if the receiver's class does not implement
* the interface Cloneable.
*/
protected native Object clone() throws CloneNotSupportedException;
为什么 Java 中的克隆对象必须进行类型转换?例如:
Vector<Integer> vec = new Vector<Integer>();
Vector<Integer> clone = (Vector)vec.clone();
为什么 clone()
return Object
引用,而不是适当的 class 的克隆?
因为clone()
方法源自对象class本身。
/**
* Answers a new instance of the same class as the receiver,
* whose slots have been filled in with the values in the
* slots of the receiver.
* <p>
* Classes which wish to support cloning must specify that
* they implement the Cloneable interface, since the native
* implementation checks for this.
*
* @return Object
* a shallow copy of this object.
* @exception CloneNotSupportedException
* if the receiver's class does not implement
* the interface Cloneable.
*/
protected native Object clone() throws CloneNotSupportedException;