What are covariant return types in Java?

Java

In general, in overriding, the method in a superclass and subclass have the same name and, parameters. But, when it comes to returning type, the method in the subclass can return the subtype of the return type of the method in the superclass.

Example

If you observe the following example super class has a method named demoMethod() and it returns a value of the type list. If we override this method the method in the subclass can return a value of the type List (which is in the superclass) or, it can also return the subtype of the List (return type of the method in the super class) such as ArrayList, Stack, Vector etc.

In this scenario the sub class method returns an ArrayList, subtype of the return type of the super class i.e. List. This sub type (ArrayList) is known as covariant type.

Example

Live Demo

class Test{
   int data =100;
   Test demoMethod(){
      return this;
   }
}
public class Sample extends Test{
   int data = 1000;
   Sample demoMethod(){
      return this;
   }
   public static void main(String args[]){
      Sample sam = new Sample();
      System.out.println(sam.demoMethod().data);
   }
}

Output

1000
raja
Published on 08-Jan-2018 09:20:57
Advertisements