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

后端 未结 4 474
独厮守ぢ
独厮守ぢ 2021-01-07 10:27

While working with the idea of overriding and overridden methods in Java I have noticed that there is some flexiblity given for the return types of such methods.

Her

相关标签:
4条回答
  • 2021-01-07 10:31

    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.

    0 讨论(0)
  • 2021-01-07 10:47

    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.

    0 讨论(0)
  • 2021-01-07 10:47

    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

    0 讨论(0)
  • 2021-01-07 10:52

    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.

    0 讨论(0)
提交回复
热议问题