Java 5.0 adds support for covariant return types, that is, when subclasses override (i.e. override) base class methods, the returned type can be a subclass of the base class method return type. The covariant return type allows a more specific type to be returned.
The sample program is as follows:
The code copy is as follows:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
class Base
{
//Subclass Derive will override this method and set the return type to a subclass of InputStream
public InputStream getInput()
{
return System.in;
}
}
public class Derive extends Base
{
@Override
public ByteArrayInputStream getInput()
{
return new ByteArrayInputStream(new byte[1024]);
}
public static void main(String[] args)
{
Derive d=new Derive();
System.out.println(d.getInput().getClass());
}
}
/*Program output:
class java.io.ByteArrayInputStream
*/