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

}}

相關文章
相關標籤/搜索