Gitnik
Gitnik

Reputation: 574

Why does cloned object have to be typecasted?

Why does cloned object in Java have to be typecasted? For example:

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

Why does clone() return Object reference, and not clone of appropriate class?

Upvotes: 0

Views: 50

Answers (1)

Shahzeb
Shahzeb

Reputation: 4785

Because clone() method originates from Object class itself .

/**
 * 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;

Upvotes: 2

Related Questions