**自 java 5 起;
我知道如果在基类中我写:
public Number doSomething(){
...
}
在子类中我可以写这样的东西
@Override
public Integer doSomething(){
...
}
但是我有一个问题。
如果在基类方法中返回 - 原始的 - 大批 - 或 Collection 。
在这种情况下如何使用协变?
最佳答案
基元之间不存在协变。没有任何原始类型是任何其他类型的子类型。所以你不能这样做
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;
}
}
对于集合
类型也是如此
class Parent {
public Collection<String> method() {
return null;
}
}
class Child extends Parent {
public List<String> method() {
return null;
}
}
请注意,泛型类型参数必须兼容(泛型中没有协变, except in bounded wildcards )。
关于java - 基元的方法返回值协方差。有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154572/