Covariant Return Type in Java

Method overriding in Java is said to be covariant with respect to return type which means that the return type is allowed to vary in the same direction as the subclass. Covariant return type feature in Java was added in Java 5.

What is covariant return type in Java

First let’s try to understand what exactly does this covariant return type mean? Before Java 5 it was not possible to change the return type of the overridden method in the sub-class meaning the method in the parent class and the overridden method in the child class should have the same name, same number and type of arguments and same return type.
Java 5 onward, because of this covariant return type feature, it is possible for the overridden method to have different return type from the method in the parent class. There is one restriction though, the return type of the sub-class method must be a subtype of the return type of the parent class method.

For example– In parent class there is a method with return type R1. In the sub-class overridden method may have a different return type R2 but R2 must be a subtype of R1.

Java covariant return type example

class Parent{
	Parent getInstance(){
		return new Parent();
	}
	void parentTest(){
		System.out.println("In parent class method");
	}
}
class Child extends Parent{
	// return type is subtype here
	Child getInstance(){
		return new Child();
	}
	void childTest(){
		System.out.println("In child class method");
	}
}
public class CovariantDemo {

	public static void main(String[] args) {
		Parent pobj = new Parent();
		Child cobj = new Child();
		pobj.getInstance().parentTest();
		cobj.getInstance().childTest();
	}
}

Output

In parent class method
In child class method

Related Posts

That’s all for the topic Covariant Return Type in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.