2014-05-19 124 views
3

我瞭解到,如果具有相同簽名的方法,我可以重寫該方法。覆蓋子類型的方法

但是,派生類中的重寫方法的返回類型可以是超類方法返回類型的子類型。如果上面提供的聲明是正確的,任何人都可以告訴我這段代碼有什麼問題嗎?

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

一個子類要覆蓋,沒有方法需要有** **確切相同簽名的方法,其壓倒一切的? –

+6

byte不是int的子類型,它們不是通過繼承關聯的,因爲它們是基元。 @Anthony,這些方法確實有相同的簽名。 – enrique7mc

+0

返回類型不是Java中方法簽名的一部分。 –

回答

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