What is covariant return type ?
Answer : In java covariant return type is when overridden method in the child class replaced by “narrower” type. As we know In Java relationship goes like Parent(Top) –> Child(Narrow than parent) –> Narrower and goes on…
Note: After release of JDK5.0 java allowed covariant return type and below this version covariant will not work.Please see example below:
package com.javahonk.covarianttest; public class CovariantReturnTest { public static void main(String[] args) { new Test3().testMethod(); } } class Test3 extends Test2 { // return type narrow down to child class object Test3 testMethod() { super.testMethod(); System.out.println("Test3 class"); return new Test3(); } } class Test2 extends Test { // return type narrow down to child class object Test2 testMethod() { super.testMethod(); System.out.println("Test2 class"); return new Test2(); } } class Test { // return type is parent class object Test testMethod() { System.out.println("Test class"); return new Test(); } }