In Java, is it possible to override methods if return types are respectively a primitive and its wrapper class?

梦想的初衷 提交于 2019-12-01 02:09:58

You can only return same type or a sub-class of the parent's return type and its known as Co-Variant return types.

The compiler lets you auto-box and unbox between primitives and wrappers but this doesn't make one a sub-class of the other. Primitives are not classes and cannot be used in the way you have.

Maybe you're getting this concept mixed up with overloading instead.

Overloading describes taking a method with the same name but different arguments; in canonical examples, an overloaded method can even return different types (although this is discouraged, as it makes code less readable).

That said...this is legal:

public int foo() {
    return 1;
}

public Integer foo(int multiplicand) {
    return 10 * multiplicand;
}

...because you're not touching the same method.

In an inheritance scheme, similar code would be illegal, per the Language Specification:

One of the inherited methods must be return-type-substitutable for every other inherited method; otherwise, a compile-time error occurs.

class Primary {
    public int foo() {
        return 1;
    }
}

// no, this does not compile!
class Secondary extends Primary {
    @Override
    public Integer foo() {
        return 1;
    }
}

So the above would work if the parent type was Object (since Integer is-an Object due to inheritance), but it wouldn't work for primitives at all, since they're not objects.

Autoboxing is nice in that it takes care of some annoyance of having to deal with objects when we only care about the primitive, but it's not a cure-all. They're still Objects at heart, and they can still point to null, whereas a primitive simply cannot.

This flexibility is not exists, because "int" is primitive datatype and "Integer" is class/wrapper of int datatype. And "int" is not a subclass of "Integer", while "Integer" is subclass of "Object" class

For first example:

Method in A:
public Object some_method() {....}
Method in B:
public Integer some_method() {....}

this type of overriding possible, but rest for two example overriding not possible.

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