Close

Java - Covariant Return Type

[Last Updated: Feb 7, 2017]

A covariant return type of a method is the one that can be replaced by a "narrower" type (subtype) when the method is overridden in a sub-class or a sub-interface.

In other words, an overridden method can have a more specific return type. As long as the new return type is assignable to the return type of the method we are overriding, it can be used.

Java supports this feature since release 5.0.




public class CovariantReturnExample {

    interface SuperType {
    }

    interface SubType extends SuperType {
    }

    interface A {
        SuperType getType ();
    }

    interface B extends A {
        SubType getType ();
    }
}

Note: Covariant returns can be used when extending classes or extending interfaces. In above example SuperType-SubType and/or A-B can be classes.




See Also