This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Because the method signature of area() is different, Square.area() does not override Rectangle.area(), but Square still inherits the area method of Rectangle. Since an int can be promoted to a long, the compiler cannot resolve which method to call.
The underlying problem is area method in Rectangle class. Method return type is long, while it expects int. Loss of precision here. That's why as long as you didn't make proper change, it will keep giving you compilation error. You should change its arguments to int, or explicit cast return value to int, or make method area expect type of long value.
When I compiled the code you posted, I did not get a compiler error saying "ambigious method". I got a compiler error saying "possible loss of precision" because length * width evaluates to a long, which does not fit into the return value of int.
Parameswaran, I did as you suggested and swapped the methods in Square and Rectangle, and I still only got a "possible loss of precision" error:
In both cases the reason is that same: the return value is a long but the method is declared to have a return value of int.
If we change the first example so that the return value is cast to an int, we get this:
This compiles and runs correctly, with an output of 25
I disagree with Edwin that the compiler does not know which method to call. Given this situation, the compiler will always attempt to choose the method with the most specific parameter datatypes. In this case, all the values that can fit in an int can also fit in a long, but other values can also fit in a long that cannot fit in an int. That makes int more specific than long. The compiler will choose the method with the most specific datatypes, if and only if the parameter datatypes of one method are clearly more specific than the parameter datatypes of the other method.
Parameswaran, if you compile your posted code again I think you'll find that it does not report an error of "ambiguous method" as you said. Perhaps you got that error from a different version of the program that you did not post. There is no ambiguous method call in this program as it is written.