使用子类型覆盖方法

时间:2014-05-19 19:52:01

标签: java method-overriding

我了解到如果方法具有相同的签名,我可以覆盖它。

但是,派生类中重写方法的返回类型可以是超类方法返回类型的子类型。如果上面提供的陈述是正确的,那么有人能告诉我这段代码有什么问题吗?

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());
    }
}

1 个答案:

答案 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.Timestampjava.util.Date

的子类