Covariant return types in Java

The Covariant return types are introduced in java 1.5V and used with Method Overriding. Covariant return type allows us to change the return type of the overriding method in child class and this return type in child class method must be a subtype of Parent class return type.

  Covariant return name come from the fact that type of the return is allowed to vary in the same direction as the subclass.


Example of Covariant return type

Create A and B two classes , A as Parent class and B as Child class. These two classes are used as return type of methods.

Example

// class used as return type
class A {

}

// sub-class of A , also used as return type
class B extends A {

}

Now create C and D Class and use A and B as a return type of methods.

class C {
	// define a method
	// return type= A
	public A getMessage() {
		System.out.println("This is method of class C");
		return new A();
	}
}

class D extends C {
	// override getMessage() of Parent class C
	/*
	 * According to Covariant return type- we can put A and its sub-class B as
	 * return type in overriding method. let us see
	 */
	public B getMessage() {
		System.out.println("This is method of class D");
		return new B();
	}
}

Create Executor class which contain main method.

class Executor {
	public static void main(String[] args) {
		// create object and call method
		C ob = new C();
		C ob1 = new D();
		ob.getMessage();
		ob1.getMessage();

	}
}
This is method of class C
This is method of class D

Compile all the file and run Executor class.
In above example class D which is the sub class of class C, the return type of getMessage() method of class D is A where as method in class D return type is B, which is sub type of A. Making it covariant return type.

Another example of Covariant retun type.

// Let us take another example of Covariant return type
class Test {
	public Object getName() {
		System.out.println("This is Method of Test(Parent class)");
		return new Object();
	}
}

class Child_Test extends Test {
	// return type= String, because String class is a Child of Object
	// class
	public String getName() {
		System.out.println("This is method of Child_Test(Child Class)");
		return new String();
	}
}

 class Executor {
	public static void main(String[] args) {
		new Test().getName();
		new Child_Test().getName();
	}
}
This is Method of Test(Parent class)
This is method of Child_Test(Child Class)