DEVFYI - Developer Resource - FYI

What is covariant return type?

Java Interview Questions and Answers (part 3)


(Continued from previous question...)

405. What is covariant return type?

A covariant return type lets you override a superclass method with a return type that subtypes the superclass method's return type. So we can use covariant return types to minimize upcasting and downcasting.

class Parent {
   Parent foo () {
      System.out.println ("Parent foo() called");
      return this;
   }
}

class Child extends Parent {
   Child foo () {
      System.out.println ("Child foo() called");
      return this;
   }
}

class Covariant {

   public static void main(String[] args) {
        Child c = new Child();
        Child c2 = c.foo(); // c2 is Child
        Parent c3 = c.foo(); // c3 points to Child
   }
}

(Continued on next question...)

Other Interview Questions