Covariant return types in Java

2.1

Before JDK 5.0, it was not possible to override a method by changing the return type. When we override a parent class method, the name, argument types and return type of the overriding method in child class has to be exactly same as that of parent class method. Overriding method was said to be invariant with respect to return type.

Covariant return types

Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but child’s return type should be sub-type of parent’s return type. Overriding method becomes variant with respect to return type.

Co-variant return type is based on Liskov substitution principle.

Below is the simple example to understand the co-variant return type with method overriding.

// Java program to demonstrate that we can have
// different return types if return type in
// overridden method is sub-type

// Two classes used for return types.
class A {}
class B extends A {}

class Base
{
    A fun()
    {
        System.out.println("Base fun()");
        return new A();
    }
}

class Derived extends Base
{
    B fun()
    {
        System.out.println("Derived fun()");
        return new B();
    }
}

public class Main
{
    public static void main(String args[])
    {
       Base base = new Base();
       base.fun();

       Derived derived = new Derived();
       derived.fun();
    }
}

Output:

Base fun()
Derived fun()


Note :
If we swap return types of Base and Derived, then above program would not work. Please see this program for example.

Advantages:

  • It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable.
  • We get a liberty to have more specific return types when overriding methods.
  • Help in preventing run-time ClassCastExceptions on returns

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.1 Average Difficulty : 2.1/5.0
Based on 11 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.