The short answer - Packages help keep your project structure well-organized, allow you to reuse names (try having two classes named Account
), and are a general convention for very large projects. They're nothing more than folder structures, but why they're used can burn beginners pretty badly. Funnily enough, with a project less than 5 classes, you probably won't need it.
What, exactly is this line doing? Why is there, what's it's role.
The line
package org.processing
is telling Java that this class file lives in a folder called /org/processing. This allows you to have a class which is fully defined as org.processing.Processor
here, and in another folder - let's say /org/account/processing, you can have a class that's fully defined as org.account.processing.Processor
. Yes, both use the same name, but they won't collide - they're in different packages. If you do decide to use them in the same class, you would have to be explicit about which one you want to use, either through the use of either import statements or the fully qualified object name.
Does this mean that compilation is always relative to directory structure?
Yes. Java and most other languages have a concept known as a classpath. Anything on this classpath can be compiled and run, and by default, the current directory you're in is on the classpath for compilation and execution. To place other files on the classpath, you would have to use another command-line invocation to your compilation:
javac -sourcepath /path/to/source MainClass.java
...and this would compile everything in your source path to your current directory, neatly organized in the folder structure specified by your package statements.
To run them, as you've already established, you would need to include the compiled source in your classpath, and then execute via the fully qualified object name:
java -cp /path/to/source org.main.MainClass
Why is all this the way it is?
Like I said before, this is mostly useful for very large projects, or projects that involve a lot of other classes and demand structure/organization, such as Android. It does a few things:
- It keeps source organized in an easy-to-locate structure. You don't have objects scattered all over the place.
- It keeps the scope of your objects clear. If I had a package named
org.music.db
, then it's pretty clear that I'm messing with objects that deal with the database and persistence. If I had a package named org.music.gui
, then it's clear that this package deals with the presentation side. This can help when you want to create a new feature, or update/refactor an existing one; you can remember what it does, but you can't recall its name exactly.
- It allows you to have objects with the same name. There is more than one type of
Map
out there, and if you're using projects that pull that in, you'd want to be able to specify which Map
you get - again, accomplished through either imports or the fully qualified object name.