Pages

Friday, July 12, 2013

Method Overriding and Covariant Return Type

While refreshing my concepts on method overriding, I came across something called "covariant return type" - I was amazed that even though I used it multiple times - but I never cared about terminology used here. Normally method overriding is achieved by redefining an inherited method to serve a different functionality, which indirectly covers parameter list (method arguments) and return type. 

Here when we talk about Covariant return type which I believe a corner case (of course a very useful) where only return type changes in a specific scenario and condition is if return type of subclass overriding method has to be subclass type or in other worlds one can change only return type of overriding method as long as return type is subclass type. I suggest read the previous sentence once again, very carefully if you are not clear about the idea.

Lets take an example to understand it a bit better:


public class SimpleDataProvider {
 public SimpleDataProvider getProvider() {
  return this;
 }
}

public class XMLDataProvider extends SimpleDataProvider{
 //As you know that getData method is available as a part of inheritance.
 //Now overriding with covariant return type as follows
 
 public XMLDataProvider getProvider(){
  return new XMLDataProvider();
 }
 
 public void printXMLDataProvider(){
  System.out.println("SampleXML Data");
 }
}

public class TestCovariantReturnType {
 public static void main(String args[]) {
  new XMLDataProvider().getProvider().printXMLDataProvider();
 }
}

In the above example as you can see Overridden method getProvider only changes return type (and no changes in argument list) - but still its allowed and valid.

I hope it helps...If I revisit..I will put a better example/explanation here.

No comments:

Post a Comment