为什么标准java类的clone()返回Object而不是实际的类型 [英] Why standard java classes's clone() return Object instead of actual type

查看:145
本文介绍了为什么标准java类的clone()返回Object而不是实际的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中允许指定函数返回的类型,例如以下代码

  public class Test {

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

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

有效。



我们来看看 ArrayList class。它已经覆盖了 clone()函数(至少我在Oracle jdk 1.7源代码中看到)

  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){
//这不应该发生,因为我们是Cloneable
throw new InternalError();
}
}

什么意思不要返回 ArrayList< E> 但只是 Object

解决方案>

向后兼容性



在Java 5之前,覆盖时返回类型无法缩小,所以 ArrayList.clone()被声明为返回 Object 。现在语言允许,他们不能使用它,因为缩小 ArrayList.clone()的返回类型会破坏ArrayList的现有子类,覆盖 ArrayList.clone()返回类型 Object


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.

这篇关于为什么标准java类的clone()返回Object而不是实际的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆