import static java.lang.System.out;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class ShadowingByImporting
{
public static void main(String[] args)throws FileNotFoundException
{
out.println("Calling println() in java.lang.System.out");
PrintWriter pw=new PrintWriter("log.txt");
writeInfo(pw);
pw.flush();
pw.close();
}
public static void writeInfo(PrintWriter out)
{
out.println("Calling pritnln() in the parameter out");
System.out.println("Calling println() in java.lang.System.out Example");
}
}
The above program is given in Khalid Mugal’s SCJP Guide,according to him by the principle of shadowing in static import the second println method in writeInfo. Method will execute twice, but when I run this following dissimilar output came.
Please somebody explain what’s the actual concept.
Calling println() in java.lang.System.out
Calling println() in java.lang.System.out Example
This has nothing to do with static imports in general,
but rather with the fact that the parameter
outofwriteInfois hiding the outer definition ofoutwhich in this case happens to be a static import.This hiding is also possible when you have