2017-10-29 19 views
0

我有這樣的代碼,它的返回語句沒有被覆蓋。 20是輸出,爲什麼會發生?任何對此的解釋都會有幫助。Java:返回語句中覆蓋的方法

class Rectangle { 
    public int area(int length, int width){ 
     return length*width; 
    } 
} 

class Square extends Rectangle{ 
    public int area(long length, long width){ 
     return (int) Math.pow(length, 2); 
    } 
} 
public class JavaApplication36 { 
    public static void main(String[] args) { 
     Square r = new Square(); 
     System.out.println(r.area(5, 4)); 
    } 
} 
+0

您沒有重寫該方法,因爲一個使用了整數,另一個使用了長整數。你的值是整數。更改方法簽名以使用整數。 –

回答

2

因爲方形區域不覆蓋矩形區域。他們的簽名是不同的。區域方法類型不同。在Square area方法上面添加@override,你將不能再編譯,但會得到一個錯誤,告訴你你沒有重寫該方法。