RiaD
RiaD

Reputation: 47620

Why standard java classes's clone() return Object instead of actual type

It's allowed in java to specify type of function return, for example following code

public class Test {

    static class Dad {
        Dad me() {
            return this;
        }
    }

    static class Son extends Dad {
        Son me() {
            return this;
        }
    }
 }

is valid.

Let's see ArrayList class. It has overridden clone() function (At least I see it in Oracle jdk 1.7 source)

public Object clone() {
    try {
        @SuppressWarnings("unchecked")
            ArrayList<E> v = (ArrayList<E>) super.clone();
        v.elementData = Arrays.copyOf(elementData, size);
        v.modCount = 0;
        return v;
    } catch (CloneNotSupportedException e) {
        // this shouldn't happen, since we are Cloneable
        throw new InternalError();
    }
}

What's the point not to return ArrayList<E> but just Object ?

Upvotes: 22

Views: 3584

Answers (2)

Stephen C
Stephen C

Reputation: 718866

One reason is backwards compatibility. The signature of the Object.clone() method was specified way back in Java 1.0, when there wasn't support for covariant return types. If they changed this fundamental method as you suggested, it could break thousands of legacy programs where the clone() method might not return an object with the same type as this.

See also:

Upvotes: 11

meriton
meriton

Reputation: 70564

Backwards compatibility.

Prior to Java 5, the return type could not be narrowed when overriding, so ArrayList.clone() was declared to return Object. Now that the language permits that, they can't use it, because narrowing the return type of ArrayList.clone() would break existing subclasses of ArrayList that override ArrayList.clone() with return type Object.

Upvotes: 15

Related Questions