Monday, December 6, 2010

Java 5 feature - Covariant return types

Now with Java 5 you can override a function and can make their return type different* which was not allowed before Java 5.
The return type of the subclass' method must be a subclass of the return type of the superclass' method. In other words you can make the return type of the subclass' method the same or less general.

Confused???? Lets understand with an example -
class Clothe { 
     public clothe getDesign() {
        System.out.println("clothe");
        return new Clothe();
    }
}
class Shirt extends Clothe {
    public Shirt getDesign() {  
     System.out.println("shirt");
     return new Shirt();
   }
}

An overridden method in a derived class can return a type derived from the type returned by the base-class method.

public class CovariantReturn {
    public static void main(String[] args) {
       clothe clothe = new clothe();
       System.out.println(clothe.getDesign());
       clothe = new Shirt();
       System.out.println(clothe.getDesign());
   } 
}   
Output:
clothe
clothe@923e30
shirt
Shirt@130c19b

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.

No comments:

Post a Comment