我了解到如果方法具有相同的签名,我可以覆盖它。
但是,派生类中重写方法的返回类型可以是超类方法返回类型的子类型。如果上面提供的陈述是正确的,那么有人能告诉我这段代码有什么问题吗?
class Base{
public int getValue(){ return 222; } //1
}
class Sub extends Base{
public byte getValue(){ return 10; } //2
public static void main(String[] args){
Base b = new Sub();
System.out.println(b.getValue());
}
}
答案 0 :(得分:3)
byte
是基本类型,而不是int
的子类型。然而,
static class Super {
public Date getValue() {
return new Date();
} // 1
}
static class Sub extends Super {
public Timestamp getValue() {
return new Timestamp(System.currentTimeMillis());
} // 2
}
public static void main(String[] args) {
Super b = new Sub();
System.out.println(b.getValue());
}
可行,因为java.sql.Timestamp
是java.util.Date