【JAVA学习路-think in java】p164:协变返回类型

package pkg;

public class p164 {
	public static void main(String[] args) {
	Mill m=new Mill();
    Grain g=new Mill().process();
	System.out.println(g);
	
//	m=new WheatMill();// SUPPORT ONLY IN JAVA SE 5.0 OR LATER
	g=m.process();
	System.out.println(g);
	}
}

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

class Wheat extends Grain{
	public String toString() {return "Wheat";}
}
// class-process
class Mill{
	Grain process() {return new Grain();}
}
class WheatMill{
	Wheat process() {return new Wheat();}
}

OUTPUT:

Grain
Grain
 

注释:

m是Mill类型,但WheatMill()定义的是WheatMill类型,属于Mill的子类。

在JAVA 5及其之后,才支持m=new WheatMill();

上述代码在JAVA 1.8中运行,m=new WheatMill();语法错误:Type mismatch: cannot convert from WheatMill to Mill

 
发布了42 篇原创文章 · 获赞 23 · 访问量 8274

猜你喜欢

转载自blog.csdn.net/Andrew_Zeng/article/details/104226152