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);
	}
}

Output

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();
       b.demoA();
 
       Subclass sub = new Subclass();
       sub.demoB();
    }
}

Output

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.