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