1.

Covariant return type in Java

Answer»

Covariant return TYPES REFER to the return type of the overriding method. It is possible to have DIFFERENT return types for overriding methods in the child class since Java 5. HOWEVER, the return type of the child class should be a subtype of the return type of the parent class.

A program that demonstrates covariant return type in Java is given as follows:

class C1 {      C1 ret()    {        return this;    }   }   public class C2 extends C1 {      C2 ret()    {        return this;    }      void DISPLAY()    {        System.out.println("This is the covariant return type");    }      public static void main(String args[])    {          new C2().ret().display();      }   }  

The output of the above program is as follows:

This is the covariant return type

The above program demonstrates covariant return type as the return type of the class C1 ret() method is C1 while the return type of the class C2 ret() method is C2 and it is method overriding while both methods have different return types.



Discussion

No Comment Found