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() {
        return new Clothe();
class Shirt extends Clothe {
    public Shirt getDesign() {  
     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();
       clothe = new Shirt();

Allowing covariant return types in Java has been in Sun's bugparade for a long time ( bug_id=4144488). Now finally, JDK 1.5 supports it.

No comments:

Post a Comment