zoukankan      html  css  js  c++  java
  • java协变类型返回

    协变类型返回也是覆盖方法的一种,jdk5开始支持的一种:子类覆盖方法返回可以是子类返回的子类,这个比较拗口

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package com.fengli;

    /**
    * 粮食类
    * @author Administrator
    */
    public class Grain {

    public String toString(){
    return "Grain";
    }

    }

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package com.fengli;

    /**
    * 小麦类
    * @author Administrator
    */
    public class Wheat extends Grain{
    @Override
    public String toString(){
    return "Wheat";
    }

    }

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.fengli;

    /**
    *协变返回
    * 子类覆盖方法返回可以是子类返回的子类,这个比较拗口
    * @author Administrator
    */
    public class CovariantReturnType {

    class Mill {

    public Grain process() {
    return new Grain();
    }
    }

    class WheatMill extends Mill {

    @Override
    public Wheat process() {
    return new Wheat();
    }
    }

    public static void main(String[] args) {
    CovariantReturnType c = new CovariantReturnType();
    CovariantReturnType.Mill m = c.new Mill();
    Grain g = m.process();
    System.out.println(g.toString());

    CovariantReturnType.Mill wm = c.new WheatMill();
    Grain g1 = wm.process();
    System.out.println(g1.toString());


    }
    }

  • 相关阅读:
    java学习day28-jQuery(常用)
    在博客园上添加bilibili视频
    参数传递 实参
    linux 下office软件推荐
    桥后总结 二
    go基础笔记-包
    Linux:Day24(上)
    Linux:Day23(下) vsftpd
    Linux:Day23(上) MariaDB SQL语句
    Linux:Day22(下) php及mysql使用基础
  • 原文地址:https://www.cnblogs.com/working/p/5646119.html
Copyright © 2011-2022 走看看