【问题标题】:Overriding Methods with the subtype用子类型覆盖方法
【发布时间】:2014-05-19 19:52:00
【问题描述】:

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

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

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

【问题讨论】:

  • 为了覆盖,该方法是否不需要与它的覆盖方法具有 exact 相同的签名?
  • byte 不是 int 的子类型,它们没有继承关系,因为它们是基元。 @Anthony,这些方法确实具有相同的签名。
  • 返回类型不是 Java 中方法签名的一部分。
  • @ant 它可以是协变的

标签: java overriding


【解决方案1】:

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 的子类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多