Below class causes a compile error at line println("Hello World!");
: The method println(String) is undefined for the type StaticImport
:
import static java.lang.Math.*;
import static java.lang.System.*;
public class StaticImport {
public static void main(String[] args) {
println("Hello World!");
out.println("Considering a circle with a diameter of 5 cm, it has:");
out.println("A circumference of " + (PI * 5) + " cm");
out.println("And an area of " + (PI * pow(2.5,2)) + " sq. cm");
}
}
Why can the pow method be accessed in java.lang.Math without explicitly importing pow , unlike the println method where the method name 'out' needs to be used ?
With static import, you can access the direct members of a class without fully qualifying it. Your static import allows you to access
out
directly, because it's a member ofSystem
, andpow
directly, because it's a member ofMath
. But neitherMath
norSystem
has the methodprintln
;PrintWriter
does (the type ofout
).Your static import...
... is equivalent to the following code, which we can see wouldn't compile: