Using covariant return types in JDK 1.5

An argument or return type in an overridden method that is made more specialized is called to be covariant. Allowing covariant return types in Java has been in Sun’s bugparade for a long time (http://bugs.sun.com/bugdatabase/view_bug.do? bug_id=4144488. Now finally, JDK 1.5 supports it.

The protected clone() method of the Object class can be overridden, made public and support shallow or deep cloning of objects. Prior to 1.5.0, the return type of clone() had to be Object and a cast was necessary:

   Dolly d2 = (Dolly) d1.clone();

Specifying any other return type than Object caused the following exception:

clone() in Dolly cannot override clone() in java.lang.Object; attempting to use incompatible return type

Now 1.5 supports overridden methods to have a different return type as long as they are a specialization of the method in the superclass.

Main.java:

public class Main
{
   public static void main(String []args) {
      Dolly d1 = new Dolly();
      Dolly d2 = null;
       
      try {
         d2 = d1.clone();
      }
      catch(CloneNotSupportedException e) {
      }
       
      System.out.println(d1);
      System.out.println(d2);
   }
}

class Dolly implements Cloneable
{
   long fur = 123456;
    
   public Dolly clone() throws CloneNotSupportedException {
      try {
         return (Dolly) super.clone();
      }
      catch(CloneNotSupportedException e) {
         throw e;
      }
   }
    
   public String toString() {
      return ""+fur;
   }
}