Covariant Return Type in Java

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.

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.

Output:


Note : If we swap return types of Base and Derived, then above program would not work

See the below example :


Output: 


Advantages:

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


This covers the concept of Covariant return type in Java, if you have any doubt or if you want to add anything , then please comment below.

Comments

Popular posts from this blog

Deploy standalone Spring MVC Application in Docker Container

Refactor Code : Separate Query from Modifier

HTTP : Must known Protocol (Part 1)