java协变类型返回
2016-07-06 10:46
471 查看
协变类型返回也是覆盖方法的一种,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());
}
}
/*
* 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());
}
}
相关文章推荐
- SpringMVC参数传递方式
- 《Spring源码分析》——JDBC章节
- java 二叉树(三)递归遍历二叉树
- spring源码分析之<context:component-scan/>vs<annotation-config/>
- 一种c#深拷贝方式完胜java深拷贝(实现上的对比)
- springmvc mybatis集成
- Java持久层框架MyBatis简单实例
- Java 内部类种类及使用解析
- JavaEE第一天_html标签
- Eclipse使用技巧
- java封装
- 一种c#深拷贝方式完胜java深拷贝(实现上的对比分析)
- java 二叉树(二)递归方式创建二叉树
- Springmvc 微信开发者模式对接
- java多态说明
- Java Web知识结构
- java.lang.NoClassDefFoundError: org/jaxen/JaxenException
- Ubuntu 下 java 版本的切换
- Java文件流关闭和垃圾回收机制
- Java 二叉树(一)普通方式的创建