Java covariant return types are used in the example
- 2020-04-01 02:54:01
- OfStack
Java 5.0 adds support for covariant return types, which can be subclasses of base class methods when subclasses override (or override) them. Covariant return types allow more specific types to be returned.
The sample program is as follows:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
class Base
{
//Subclass Derive overrides this method, setting 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());
}
}