Java协变返回类型

来源:互联网 发布:webservice 返回json 编辑:程序博客网 时间:2024/06/09 14:15

协变返回类型

子类重写父类方法时,返回类型可以是基类的子类

实例

class Base{    //子类Derive将重写此方法,将返回类型设置为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());    }}
原创粉丝点击