Why can't Java figure it out based on the folder structure?
It seems that the mapping to packages is already specified by the root source folder plus the path to that particular file.
It is completely coupled, and doing a refactor without an IDE is absolutely tedious - although updating the references to that file would be anyway, but it could at least partially be figured out by the compiler rather than specifying the package at the file level.
The main reason for having package is to avoid Name collisions..
So,if you want the compiler to figure out the
ArrayList
class automatically it won't be able to do it cause you can have your own class namedArrayList
.How would compiler know which class to use.So,you need have a package name defined.This coupling of directory structure and package name declaration is not a requirement of the Java language. It is imposed by compiler implementations. As explained in Chapter 7 of the Java Language Specification, compilation units do not need to be stored in a file system at all; they can just as easily be in a data base. Also, the language allows package names to contain characters that may be illegal in directory names in the underlying file system.
From the JLS:
Most of our compilers evidently use a variation of this "extremely simple" approach, whereby source and binary code are stored in parallel hierarchies. But nothing about the language requires this.
There is no tight coupling required by the Java Language Specification between a directory/folder structure and the name of a package. Here is a quote from the Java Online Tutorial:
All the IDE's that I know of do manage packages according to a directory structure, but if you really wanted to develop without an IDE and according to a folder structure of your own choosing, it is still possible to do so.
Folder structures and packages are different although related. For example a src folder called 'src', which holds the entire packages hierarchy may need to be part of the packages. This is especially from the perspective of IDEs like eclipse, where you can create source folders with any heir achy but not related to your package structures.
Another useful info from JLS as a rule that compilers may require:
From the JLS 7.2
Also read about Compilation Units , closely related to your question.
Note: When you compiling from the command line, by default each class will be put in the same location as the corresponding source file, but if you use the "-d" option the compiler will build the appropriate output directory.