/*
As is, program compiles okay. When line (1) commented out, compile error
(as I would expect):
ImportAnomaly.java:41: cannot resolve symbol
symbol : class URL
location: class ImportAnomaly
URL url = ia.getClass().getResource("Face0.gif"); // (3)
^
When lines (1), (3), and (4) are commented out, the compile error goes away.
HOWEVER, with these lines commented out, line (2) is STILL creating an
(intermediate) object of class URL, and feeding it to the ImageIcon class'
constructor as an argument. Why doesn't line (2) REQUIRE line (1)? How
does the ImageIcon constructor know that the argument is of class
java.net.URL when, with line (1) commented out, that class is "alien" to
the program?
*/
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.net.URL; // (1)
publicclass ImportAnomaly {
publicstaticvoid main(String[] args) {
ImportAnomaly ia = new ImportAnomaly();
Icon icon1 =
new ImageIcon(ia.getClass().getResource("Face0.gif")); // (2)
URL url = ia.getClass().getResource("Face0.gif"); // (3)
Icon icon2 = new ImageIcon(url); // (4)
}
}
It tells the compiler: Everytime you find a class name you don't know try looking in the import list if you can find the "path" (=package + classname) of that class there.
So: If you WRITE "URL", the compiler does not know a class called URL, it takes a look at your imports and sees it in there. If you use import java.net.*;, then it looks at al the classes in this package.
So why does line (2) not require an import? Well, the compiler knows that ia.getClass().getResource("Face0.gif") returns a java.net.URL.