所谓协变返回类型就是:如果在继承时有返回值得方法发生覆盖,那么子类中的该方法的返回类型可以是父类中该方法返回类型的子类型,该特性是J2SE 5的新特性。
<span style="font-family:Courier New;font-size:14px;">class A {
protected A process() {
return new A();
}
public String toString() {
return "A class";
}
}
class B extends A {
@Override
public B process() {
return new B();
}
public String toString() {
return "B class";
}
}
public class ReturnType {
public static void main(String[] args) {
A a = new A();
B b = new B();
System.out.println(a.process());
a = b.process();
System.out.println(a.toString());
}
}</span>
协变返回类型的本质是多态。