Monday 31 October 2016

Java Source World: Covariant Return Type in Java

Covariant Return Type in Java | Java Source World
                                                                    Javasourceworld                   A Java quick reference blog 




Covariant Return Type in Java


The covariant return type specifies that the return type may vary in the same direction as the subclass.

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:

Example: 

package com.core;
class A{
     
      A getA(){
            return this;
      }
}
class B extends A {
     
     
      B getA(){
            return this;
      }
      void message(){
            System.out.println("Message me");
      }
}

public class TestCovariant {
      public static void main(String[] args) {
            new B().getA().message();
      }
}
Output:Message me


As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.


Advantages:
  • Covariant return type helps to maintain backward compatibility.
  • We can always work at the appropriate level of abstraction



Also you may like the fallowing posts:

Fallow Spring Tutorials:



                                                               Javasourceworld                   A Java quick reference blog

No comments:

Post a Comment