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.
Here is a bit of theory:
"The return type of an overriding method in the derived class can be the same, or a subclass of the return type of the overridden method in the base class. The return type of such an overriding method is known as a covariant return type."
Example below supposes that B extends A.
Method in A:
public Object some_method() {....}
Method in B:
public Integer some_method() {....}
So, we see that some_method() in B overrides some_method() in A since Integer is a subclass of Object.
I wonder whether the following flexibility exists and whether the following will correctly work because of auto-boxing and unboxing:
Method in A:
public Integer some_method() {....}
Method in B:
public int some_method() {....}
OR
Method in A:
public int some_method() {....}
Method in B:
public Integer some_method() {....}
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 Object
s 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.