问题描述
为什么必须对Java中的克隆对象进行类型转换? 例如:
Vector<Integer> vec = new Vector<Integer>();
Vector<Integer> clone = (Vector)vec.clone();
为什么clone()
返回Object
引用,而不返回适当类的克隆?
1楼
因为clone()
方法源自Object类本身。
/**
* 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;