method return value covariance for primitives. Is it works?

对着背影说爱祢 提交于 2019-12-19 11:59:14

问题


**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(){
    ...
}

But I have a question.

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

How can I use covariant at this case?


回答1:


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;
    }
}

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;
    }
}

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).




回答2:


  1. primitive : No
  2. array : Only if its a subtype of the parent's array type
  3. or Collection : Same thing as 2


来源:https://stackoverflow.com/questions/22154572/method-return-value-covariance-for-primitives-is-it-works

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!