Should the packages match the subdirectories in which the Java file is located?

I am writing some practical programs for my java certification this morning and noticed that I made a mistake in the name of the package, so it did not match the subdirectory in which the java file was located. I compiled the code waiting for an error, but the whole compiled file is even a warning.

I was looking for a little language, and most of the pages I read said that the package name should match the subdirectory. My experience shows that this is not the case.

When I tried to run the program, it did not work because the .class file was in the wrong directory. I moved it to the correct directory and received this error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/sample/directory /doesnt/even/exist/OtherPackageMemberModifiers (wrong name: com/sample/chap01/O therPackageMemberModifiers) 

So, I think I see that Java code will compile if the package and subdirectory do not match, but there seems to be no way to run the code if you do this. It is right?

+8
java package
source share
1 answer

The package name must match the directory name so that the class file is found correctly. It does not have to match the directory name at compile time for some compilers (e.g. javac), although others (e.g. Eclipse) will at least give a warning.

"The way to run the code if you do this" is to create a directory structure and put it there manually - the class file itself is fully valid.

Note that if you use the -d flag, javac will create an appropriate directory hierarchy for you, regardless of the source location. For example:

 javac -d bin ClassInPackage.java 

will create all the necessary directories under bin to match the package declared in ClassInPackage.java .

Having said all this, I still highly recommend that you map the source directories to the packages, even if you can do without it :)

+14
source share

All Articles