class Super {
public Integer getLength() {
return new Integer(4);
}
}
public class Sub extends Super {
public Long getLength() {
return new Long(5);
}
public static void main(String[] args) {
Super sooper = new Super();
Sub sub = new Sub();
System.out.println(sooper.getLength().toString() + "," + sub.getLength().toString());
}
}运行上述代码,输出是
# 4,4# 4,5# 5,4# 5,5编译失败
方法重写时,如果签名一致,返回类型必须一致,如果不一致,那么子类的返回类型只能继承自父类的返回类型。
Long明显不是继承自Integer,所以,编译会失败
Long明显不是继承自Integer,所以,编译会失败