What is covariant return type?

Q

What is covariant return type?

✍: Guest

A

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
   }
}
_break_

406. What is the result of the following statement?

int i = 1, float f = 2.0f;
i += f; //ok, the cast done automatically by the compiler
i = i + f; //error
The compound assignment operators automatically include cast operations in their behaviors.

2013-03-07, 2035👍, 0💬