方法返回原语的协方差。它有效吗? [英] method return value covariance for primitives. Is it works?

查看:140
本文介绍了方法返回原语的协方差。它有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

**因为java 5;

**since java 5;

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

I know that if in the base class I write:

public Number doSomething(){
...
}

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

in the child class I can write something like this

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

但我有一个问题。

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

If in base class method returns - primitive - array - or Collection.

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

How can I use covariant at this case?

推荐答案

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

There's no covariance between primitives. No primitive type is a sub type of any other. So you can't do this

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

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

出于同样的原因,<$ $的相应数组类型c $ c> int 和 short 也不是协变的。

For the same reason, corresponding array types for int and short also are not covariant.

对于数组类型,它类似于你的数字示例

With array types, it's similar to your Number example

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

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

同样适用于 Collection types

Similarly for Collection types

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

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

注意泛型类型参数必须兼容(否仿制药中的协方差,除了有界通配符)。

Note the generic type argument has to be compatible (no covariance in generics, except in bounded wildcards).

这篇关于方法返回原语的协方差。它有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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