What is Covariant return types in Java?

While overriding the methods in subclass name, arguments, and return type must me same as super class method until before Java 1.5. Overriding method is said to be invariant with respect to argument types and return type of super class. Suppose if we changing any argument types then its not actually overriding but its method overloading. Complete method signature must be as same as super class method for overriding till before Java 1.5.

This has been relaxed from Java 1.5, where subclass method can have different return type but only condition is subclass can return type must be a sub-type of super-class return type. Lets see simple example for Covariant return types in Java and how it works,


public class ClassA {
 
 public ClassA getInstance(){
  return new ClassA();
 }
 
 public void sayHello(){
  System.out.println("Hello Class A ");
 }
}



public class ClassB extends ClassA{
 
 @Override
 public ClassB getInstance() {
  return new ClassB();
 }
 
 @Override
 public void sayHello() {
  System.out.println("Hello Class B ");
 }
 
 public static void main(String[] args) {
  ClassA obj = new ClassB().getInstance();
  obj.sayHello();
 }
}


OUTPUT:


Hello Class B 



If we seen in above example we are overriding getInstance() method from super class ClassA. But the return type is different from super class method where we are returning subclass instance here. Even though we are overriding return types are different in both the methods. This is called as Covariant return types in Java.

By this we can remember that from Java 1.5 overriding method can different return type with single condition ie., subclass can return type must be a sub-type of super-class return type.






No comments :

Post a Comment