Reputation: 1406
I'm just curious about something. Say I have the following environment:
Folder structure -
projects \ prj1 \ src \ pkgs \ main (contains Main.java)
\ test (contains TestClass.java)
Main.java -
package pkgs.main;
import pkgs.test.TestClass;
class Main {
public static void main(String[] args) {
TestClass tc;
}
}
Java shell based compilation commmands -
javac -d ..\cls -sourcepath ..\src ..\src\pkgs\main\Main.java
java -classpath ..\cls pkgs.main.Main
If I then make a .java code file called Default.java, that doesn't have a package statement -
public class Default {}
and place this file in the src folder, how can a class file such as Main.java access this Default class? I tried using the following import statements, but neither worked, causing compilation errors:
Main.java -
package pkgs.main;
// import Default; (causes many compilation error messages)
// import .Default; (causes "identifier expected" compilation error)
I also moved the Default.java file from the src folder, in to the same folder that contained Main.java, but that didn't work either. I appreciate that this whole idea seems like bad design, but I'm only doing it in order to learn a bit more about how the package and import statements work, alongside the project folder structure. Thanks.
Upvotes: 3
Views: 4702
Reputation: 23593
To avoid two steps of indirection, the essence of the accepted answer is that according to the specification:
It is a compile time error to import a type from the unnamed package.
Which means that if you're not in the unnamed (aka default) package, you can't reach classes in the unnamed/default package, unless you are prepared to turn to reflection.
However, if you're in the unnamed/default package, you don't need to import anything, just don't forget to set the classpath, e.g. javac -cp "." ABC.java
Upvotes: 3