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