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
outdirectly, because it's a member ofSystem, andpowdirectly, because it's a member ofMath. But neitherMathnorSystemhas the methodprintln;PrintWriterdoes (the type ofout).Your static import...
... is equivalent to the following code, which we can see wouldn't compile: