Java Covariant Return Type

Before Java 5, it was not possible to override a method by changing the return type. When we override a method it is compulsory that the method definition is the same as the parent class method. The method which is overriding is known as to invariant return type

After Java 5, we can override a method by changing the return type but the return type of overridden method must be the same or subtype of the overriding method’s return type.

Covariant return type means a type that is either the same or a subtype of the supertype.

Below program illustrate the covariant return type declaration –

Java Covariant Return Type, Covariant Return Type

Example of Java Covariant Return Type

package test;

class A {
	// create class A
}

class B extends A {
	// create class B which is derived from class A
}

class Base {

	Base() {
		System.out.println("Base class constructor");
	}

	public A getMessage() {
		System.out.println("returning from base class");
		return new A();
	}

}

class Derive extends Base {

	Derive() {
		System.out.println("Derive class constructor");
	}

	@Override
	public B getMessage() // overrriding getmessage method but return type is different
	{
		System.out.println("returning from derive class");
		return new B();
	}

}

public class TestCovariant {

	public static void main(String[] args) {

		Derive d = new Derive();
		Base b = new Base();
		Base base = new Derive();
		d.getMessage();
		b.getMessage();
		base.getMessage();

	}

}
Example Output

Share