当前位置: 代码迷 >> java >> 为什么必须对克隆的对象进行类型转换?
  详细解决方案

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

热度:12   发布时间:2023-08-02 11:13:32.0

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

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

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

因为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;
  相关解决方案