**自java 5;
我知道如果在基类中我写:
public Number doSomething(){
...
}
在子类中我可以写这样的东西
@Override
public Integer doSomething(){
...
}
但我有一个问题。
如果在基类方法中返回 - 原始的 - 数组 - 或收藏。
在这种情况下如何使用协变?
答案 0 :(得分:8)
原语之间没有协方差。没有原始类型是任何其他类型的子类型。所以你不能这样做
class Parent {
public int method() {
return 0;
}
}
class Child extends Parent {
public short method() { // compilation error
return 0;
}
}
出于同样的原因,int
和short
的相应数组类型也不是协变的。
对于数组类型,它与您的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)