Why do Java source files go into a directory structure?

回眸只為那壹抹淺笑 提交于 2019-12-08 02:01:05

问题


as weSuppose that I am creating a Java project with the following classes

  1. com.bharani.ClassOne
  2. com.bharani.ClassTwo
  3. com.bharani.helper.HelperOne
  4. com.bharani.helper.support.HelperTwo

with files put immediately under the folder 'src'

  1. src/ClassOne.java
  2. src/ClassTwo.java
  3. src/HelperOne.java
  4. src/HelperTwo.java

and compile them using the command

$ javac -d classes src/*.java (assuming that classes directory exists)

The compiler compiles these files and put the class files in appropriate sub-directories inside the 'classes' directory like this

  1. classes/com/bharani/ClassOne.class
  2. classes/com/bharani/ClassTwo.class
  3. classes/com/bharani/helper/HelperOne.class
  4. classes/com/bharani/helper/support/HelperTwo.class

Because the spec mandates that the classes should go inside appropriate directory structure. Fine.

My question is this: When I use an IDE such as Eclipse or NetBeans, they create the directory structure for the source code directory ('src' directory here) as well. Why is that? Is it mandatory? Or, is it just a convention?

Thanks.


回答1:


Mainly convention. It makes sense for the source to mirror the binary structure.

Also, if you have two classes with the same name (but in different packages), how would you store the source if not in different directories?

Keeping the source in just one folder is fine for small projects, but once you have a larger project (hundreds of classes), grouping the source into packages makes things far more manageable.




回答2:


Is it mandatory? 

No

Or, is it just a convention?

Yes, to reflect your package structure in your source tree.

I always thought that Java's package is a little bit broken:

it seems to be hierachical, but it is not.

it is a simple (unique) prefix to define seperate plain namespaces.




回答3:


I thought it was mandatory, but your experience suggests otherwise. Either way, it's just common sense, right? Large projects have so many source files - why make life more complicated by having different structures for your source and your class files?



来源:https://stackoverflow.com/questions/3004835/why-do-java-source-files-go-into-a-directory-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!