covariant return type
package com.fallsown.covariant;
/**
* covariant return type:基类中某个函数在派生类中可以override,并且返回值得是基类中那个函数返回值的子类。
* java SE5之后改动
* 以前版本不支持
* @author: 红烧鲈鱼
* @date: 2021/3/13
*/
class Grain {
public String toString() { return "Grain"; }
}
class Wheat extends Grain {
public String toString() { return "Wheat"; }
}
class Mill {
Grain process() { return new Grain(); }
}
class WheatMill extends Mill {
Wheat process() { return new Wheat(); }
}
public class CovariantReturn {
public static void main(String[] args) {
Mill m = new Mill();
Grain g = m.process();
System.out.println(g);
// 向上转型 - 相当于m指向了一个派生类
m = new WheatMill();
// 运行了派生类中的方法 - m.process()返回了Wheat的引用
g = m.process();
System.out.println(g);
}
} /* Output:
Grain
Wheat
*///:~
热水有益于身体健康

浙公网安备 33010602011771号