Introduction
The covariant return type In Java allows a subclass method to return a more specific type than the return type of the overridden method in the superclass. This means that if a method is overridden in a subclass, then the return type of the overriding method can be a subtype of the return type of the overridden method.
In this article, we will learn about covariant return type in Java. This topic is important if you wish to master method overloading. We will understand the need for using the covariant return type in Java by considering some simple examples.
Must Read, Multithreading in java, Fibonacci Series in Java
What is a Covariant Return Type in Java?
Covariant return type refers to the return type of an overriding method. This statement means that the return type of the sub-class method can be a covariant(may vary in the same direction) of the parent method’s return type.
Covariance means that the two return types should be of similar type and not vary so much in properties. For example, String is a covariant of the object data type. The feature of covariant return type in java was introduced in Java 5. Before java 5, we could not do method overriding by changing the return type. The overriding method must be invariant for the return type.
However, Java 5 introduced this new return type feature while overriding. Now a derived class function need not have the same return type as the overridden function of the parent class.
Note1: We use covariant return types only in the case of non-primitive return types. Secondly, the child method’s return type must be a subtype of the parent method’s return type.
Note2: When dealing with covariant return types, make sure that the methods present in the child class must not override the parent class’s methods and vice versa.
Let us take some simple examples of covariant return type in java.
Example 1
File Name: BMW.java
Code:
Output
This is the BMW class.
Try it on online java compiler.
Explanation
Look at the code carefully. We create a Car class with a get() method. We then derive a BMW class from the Car class. In the BMW class, we override the get() method. But see, instead of having the return type as Car, we return an object of type BMW. This code works perfectly fine even though the return type of children and parent did not match. However, BMW as a return type works alright because it is a subclass of the Car class.
Example 2
Code
Output
Hi, this message is sent by the parent class.
Hello, this message is sent by the child class.
Explanation
The interesting thing to note about this example is that we created our own covariant data types. An object of class B is covariant to the object of class A. The reason being B is a subclass of A. So when overloading the fun() function in the child class, we have created an object of B class. As you can see, the code runs perfectly and gives the desired output.
Also see, Duck Number in Java and Hashcode Method in Java