2017-10-29 77 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,你将不能再编译,但会得到一个错误,告诉你你没有重写该方法。