简体   繁体   中英

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 ?

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 .

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM