Today, I got a problem compiling a java source code. The source code uses several classes in another package so I use “import fruit.*” to try to import all classes from the package fruit. But the compiler complains “source file .\App.java does not contain class App”. App.java is right in current directory and contains the classes in package fruit. I’ve already compiled App.java and put the generated classes in .\fruit so I thought javac should be able to import those classes. However, the fact is javac does not import those classes in .\fruit and try to load the source file .\App.java and compile it. When I changed the import statement from import wildcard to import specific classes, no problem occurred. How does this happen?
I think there must be some order when javac searches a class. When meeting the importing statement, it will scan the package directory to see if the classes are there. If not found, javac will report an error. If importing specific classes and those classes are found, javac will use those classes even the source files for the classes exist in current directory. If importing wildcard, javac will first try to load source file and compile it to get the classes. If the source file can be read but cannot be compiled(e.g., classes not found in the source file), javac will fail. If the source file can not be found, javac will look up the classes in the package specified by the wildcard import statement and import the classes from there. That explains why import wildcard fails but import specific classes succeed. To use wildcard import, just remove the source files for the package from current directory.