Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java allow a subclass to redefine the return type of a method?

Tags:

java

This is valid Java:

public interface Bar {
    Number getFoo();
}

public class MyBar implements Bar {
    @Override
    public Integer getFoo() {
        return Integer.MAX_VALUE;
    }
}

and I know why it is valid Java, since Integer is a sub-class of Number. But I am wondering if there are any good reasons why the language allows a sub-class to redefine the return type? Are there places where this is a useful thing? Wouldn't best practice dictate that this should be:

public class MyBar implements Bar {
    @Override
    public Number getFoo() {
        return Integer.MAX_VALUE;
    }
}
like image 596
DaveJohnston Avatar asked Dec 09 '22 12:12

DaveJohnston


1 Answers

Because Integer is a sub-type of Number, it can be used as a replacement in the return type.

I believe that is called Covariant return types, see here.

You would want to use it in situations where the subclass wants to be more specific than the parent class and add restrictions, for example, for classes that might sub-type it.

So, apart from Jeff Storey's example, the following would be possible

public static class MyFoo extends MyBar {

    @Override
    public Integer getFoo() {
        return super.getFoo();
    }

}

but not

public static class MyFoo extends MyBar {

    @Override
    public Number getFoo() { // compile error: The return type is incompatible with MyBar.getFoo()
        return super.getFoo();
    }

}
like image 98
Sotirios Delimanolis Avatar answered Dec 11 '22 10:12

Sotirios Delimanolis