Covariant return type in Java

Java Programming Java8Object Oriented Programming

Covariant return type refers to return type of an overriding method. It allows to narrow down return type of an overridden method without any need to cast the type or check the return type. Covariant return type works only for non-primitive return types.

From Java 5 onwards, we can override a method by changing its return type only by abiding the condition that return type is a subclass of that of overridden method return type.

Example

Following example showcases the same.

Live Demo

class SuperClass {
   SuperClass get() {
      System.out.println("SuperClass");
      return this;
   }
}

public class Tester extends SuperClass {
   Tester get() {
      System.out.println("SubClass");
      return this;
   }

   public static void main(String[] args) {
      SuperClass tester = new Tester();
      tester.get();
   }
}

Output

Subclass
raja
Published on 26-Jul-2018 06:48:53
Advertisements