Covariant Return Types in Java

dolphin's dance on Flickr

(Photo: dolphin’s dance by kalandrakas

This article, Covariant Return Types, from java.sun.com and reprinted in a nicer format by Java Tips, explains well what covariant return types are.

You cannot have two methods in the same class with signatures that only differ by return type. Until the J2SE 5.0 release, it was also true that a class could not override the return type of the methods it inherits from a superclass. In this tip you will learn about a new feature in J2SE 5.0 that allows covariant return types. What this means is that a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. This feature removes the need for excessive type checking and casting.

An example is:

public class Shape {
  private Shape shape;
  public Shape getShape() { return shape; }
}

public class Circle extends Shape {
  private Circle circle;
  @Override
  public Circle getShape() { return circle; }
}

Not the best example but a succinct one. 🙂