Covariant Return Type in Java

In this article, we will learn about covariant return types in Java.

Before Java version 5.0, we could not change the return type of an overridden method but a new method was introduced in JDK 5.0, called covariant where we could change the return type of the overridden method. The return type must be non-primitive. (i.e., it should be a sub-type of the overridden class).

Program:

Output:

Explanation:

In the above program, we created three classes: class ‘Employee’, class ‘Manager’, and class ‘Main’.

In class ‘Employee’, we defined a function, namely ‘work’ and its return type is its class type, i.e., ‘Employee’. In class ‘Manager’, we defined a function whose name is ‘work’ and its return type is its class type ( ‘Manager’ ).

In this case, the Class Manager’s work() method overrides the class Employee’s work() method. And, both methods have a different return type.

‘this’ returns the current object’s class reference. class Employee’s work() method returns ‘Employee’ class type value whereas class Manager’s work() method returns ‘Manager’ class type value. In the third class ‘Main’, we created an object of class ‘Manager’ (‘Manager’ inherits the properties of class ‘Employee’) and call the method using its object. Now, it always prints the class ‘Manager’ function statements instead of class ‘Employee’ because class ‘Manager’ overrides the other class.

How are Covariant return types implemented?

Java doesn’t allow you to change the return type of overridden method but JVM always allows you to change the return type of overridden methods. JVM includes return type in addition to argument types of Employee method for resolution. Classes can have two or more methods, differing only by their return type.

The major advantage of covariant return type is that it reduces the downcasting from the parent class to the child class. It prevents errors at runtime such as ClassCast Exceptions.

So, that’s all about the covariant of return types in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *