Java covariant return type

covariant return type:基类中某个函数在派生类中可以override,并且返回值得是基类中那个函数返回值的子类。


Java SE5 adds covariant return types, which means that an overridden method in a derived class can return a type derived from the type returned by the base-class method


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 = new WheatMill();
g = m.process();
System.out.println(g);
}
} /* Output:
Grain
Wheat
*///:~

你可能感兴趣的:(java,String,Class,output,Types)