方法返回原语的协方差。它有效吗?

时间:2014-03-03 18:36:59

标签: java covariance

**自java 5;

我知道如果在基类中我写:

public Number doSomething(){
...
}

在子类中我可以写这样的东西

@Override
public Integer doSomething(){
    ...
}

但我有一个问题。

如果在基类方法中返回   - 原始的   - 数组   - 或收藏。

在这种情况下如何使用协变?

2 个答案:

答案 0 :(得分:8)

原语之间没有协方差。没有原始类型是任何其他类型的子类型。所以你不能这样做

class Parent {
    public int method() {
        return 0;
    }
}

class Child extends Parent {
    public short method() { // compilation error
        return 0;
    }
}

出于同样的原因,intshort的相应数组类型也不是协变的。

对于数组类型,它与您的Number示例

类似
class Parent {
    public Number[] method() {
        return null;
    }
}

class Child extends Parent {
    public Integer[] method() {
        return null;
    }
}

类似于Collection类型

class Parent {
    public Collection<String> method() {
        return null;
    }
}

class Child extends Parent {
    public List<String> method() {
        return null;
    }
}

注意泛型类型参数必须兼容(泛型中没有协方差,except in bounded wildcards)。

答案 1 :(得分:0)

  1. 原语:否
  2. array:仅当父类的数组类型的子类型
  3. 或Collection:与2
  4. 相同