What is co-variant return type in java?
A co-variant return type allows to override a super class method that returns a type that sub class type of super class method’s return type. It is to minimize up casting and down casting.
The following code snippet depicts the concept:
class Parent
{
Parent sampleMethod()
{
System.out.println(“Parent sampleMethod() invoked”);
return this;
}
}
class Child extends Parent
{
Child sampleMethod()
{
System.out.println(“Child sampleMethod() invoked”);
return this;
}
}
class Covariant
{
public static void main(String args[])
{
Child child1 = new Child();
Child child2 = new child1.sampleMethod();
Parent parent1 = child1.sampleMethod();
}
}