为什么克隆对象必须进行类型转换?

时间:2015-07-28 00:28:00

标签: java casting clone

为什么Java中的克隆对象必须进行类型转换?例如:

Vector<Integer> vec = new Vector<Integer>();
Vector<Integer> clone = (Vector)vec.clone();

为什么clone()会返回Object引用,而不是克隆适当的类?

1 个答案:

答案 0 :(得分:2)

因为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;