Home » Java programming language

Covariant return type in java

Learn: What is Covariant return type in java? Here, we are going to learn about Covariant return type in detail and what is the utilization of Covariant return type?
Submitted by Preeti Jain, on April 24, 2018

Covariant return type

The covariant return type is that return type which may vary in parent and child class (or subclass).

Before JDK5 java does not support covariant return type it means (parent return type and child return must be same).

In JDK5 onwards java supports covariant return type it means (parent return type and child return can vary if we define).

The covariant return type is useful in method overriding when we override a method in the derived class (or subclass) then return type may vary depending on JDK (Before JDK5 return type should be same and after or JDK5 we can consider return type can vary).

Example -1

class ParentClass1{
	int a=10,b=20;
	public int sum(){
		return a+b;

class ChildClass1 extends ParentClass1{
	int c=30, d=40;

	public int sum(){
		return (c+d);
	public static void main(String[] args){
		ChildClass1 cc1 = new ChildClass1();
		ParentClass1 pc1 = new ParentClass1();
		int e = cc1.sum();
		int f = pc1.sum();
		System.out.println("Child class Sum is :"+e);
		System.out.println("Parent class Sum is :"+f);


D:\Java Articles>java ChildClass1
Child class Sum is :70
Parent class Sum is :30

Example -2

class ParentA {}
class ChildB extends ParentA {}
class Base
    ParentA demoA()
        System.out.println("Base class demo");
        return new ParentA();
class Subclass extends Base
    ChildB demoB()
        System.out.println("Subclass demoB");
        return new ChildB();
class MainClass
    public static void main(String args[])
       Base b = new Base();
       Subclass sub = new Subclass();


D:\Java Articles>java MainClass
Base class demo
Subclass demoB

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.