trying to overload the java.lang.Math.sqrt static method for int type :
import static java.lang.Math.sqrt;
class Test
{
private static double sqrt(int n)
{
return sqrt(1.0 * n);
}
public static void main(String[] args)
{
System.out.println(sqrt(1));
}
}
an odd error arises :
Test.java:7: sqrt(int) in Test cannot be applied to (double)
return sqrt(1.0 * n);
^
1 error
But when explicitly referencing the java.lang.Math.sqrt method all is going fine :
class Test
{
private static double sqrt(int n)
{
return Math.sqrt(1.0 * n);
}
public static void main(String[] args)
{
System.out.println(sqrt(1));
}
}
The compiler used is the standard javac, version 1.6.0_16.
So the questions are :
- Why is the compiler not able to resolve the overloading in the first case ?
- Where does this behavior is specified in the java language specifications ?
Thanks in advance.
You can only overload methods in the same class. I.e. if you import a static method of another class and then define your own method with the same name, there will be no overload resolution. The imported version of the method will simply be ignored.
Regarding where this behavior is specified: The language specification defines overloading like this:
Note that it says “two methods of a class”. So methods imported from another class are simply not considered.
So since your definition is not an overload of Math.sqrt, it shadows it as per section 6.3.1 of the definition: