java协变类型返回

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

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

package com.fengli;spa

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

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

}jdk

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

package com.fengli;static

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

}process

 

/*
* 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());

}}

相关文章
相关标签/搜索