Since all java class files are put into a directory that matches the classes package, why would each class then require the package declaration at the top? Shouldn't the compiler be able to get the package from the directory structure?
Asked
Active
Viewed 159 times
1
-
You might have classes which are in the same package, but under different directories. – Konstantin Yovkov Dec 30 '15 at 12:20
-
1how would the compiler know which directory is the root of the source tree? – wero Dec 30 '15 at 12:20
-
This is a very interesting question and it's observant of you to note this! But it seems like it has been asked before. – Lii Dec 30 '15 at 12:31
-
There are many duplicates of this questions, and there are many good answers as well. But i think [http://stackoverflow.com/a/17798226/3227510](http://stackoverflow.com/a/17798226/3227510) explained it better. – Raj Kantaria Dec 30 '15 at 12:31
-
1I suggest you use an IDE. This way it will add things like `package` and `import` for you. While adding the package might seem redundant, it provides an additional check that the file is in the right directory. – Peter Lawrey Dec 30 '15 at 12:34
2 Answers
6
Because the source files don't need to be in the same directory structure. You could (theoretically, not that it makes much sense) have all the source files in the same directory, and after compilation they would end up in the proper package-based structure.

Kayaman
- 72,141
- 5
- 83
- 121
0
It is a good practice for developers to differentiate or group set of classes based on its functionality. Eg - DAO classes in dao package, Service classes in service package etc.
Well, on the same line - You could write everything for a program in a single class as well!

aksappy
- 3,400
- 3
- 23
- 49