Understanding Covariant Return types in Java

A tutorial on what is covariant return types in Java

One of the features introduced in Java 1.5 was covariant return types.To put it simply covariant return types means that the return type of an overriden method can be a subclass of the method's return type in the superclass.

As an example consider the case where we have a TestClass that has a method which has as a return type a ReturnClass

public class TestClass {
    
//other methods go here
    protected ReturnClass returnANewClass(){
        return new ReturnClass();
    }
}

and the ReturnClass could be:

public class ReturnClass {
    //other methods go here
    @Override
    public String  toString(){
        return "Return class in the super class";
    }
}

Covariant return types means that in a subclass of the TestClass the overriden method returnNewClass() can have as a return type a subclass of the ReturnClass:

public class TestSubclass extends TestClass{

    @Override
    protected ReturnSubclass returnANewClass() {
        return new ReturnSubclass();
    }
    
    
}

and the ReturnSubclass could be:

public class ReturnSubclass extends ReturnClass{

    @Override
    public String toString() {
        return "return subclass";
    }
    
    
}

Copyright © 2012 Design and Development Nikos Lianeris

  • 0
  • 0