Working With Packages

Packages are more or less Java's equivalent of namespaces in other languages like C++ and XML. Putting classes in a particular package ensures that there won't be a name conflict between your class and another. For instance, there are at least two Date classes commonly used in Java code. One is java.util.Date. The other is java.sql.Date. Each one of them is inside a package (java.util and java.sql respectively), so they don't conflict. However, if neither were in a package, the libraries wouldn't compile. The compiler would interpret one as a re-definition of the other. Freak out. Packages also allow a logical organizational abstraction for related groups of Java classes and interfaces. To specify a package for your class or interface, the very first line of your Java file must read "package [name of package];".

I won't bother going further with packages as a language feature. There are many resources online and elsewhere that can help you understand this very mundane aspect of Java. If you're going the online route, you can always start with a Google search or Wikipedia If you're going to use packages at all, this is a must; there are a few weird caveats to using them.

Eclipse has some package-related features I will talk about, though. The first is the Package Explorer. As you might guess by its name, the Package Explorer presents your project to you with a focus on its Java package structure. If you've been using Eclipse already, you'll probably notice that new classes you create don't simply appear. They appear under a node in the hierarchy called "default package". This is because if you don't specify a package for your class, it will be grouped with all other non-packaged classes in this default package.

You can add a new package in Eclipse by right-clicking on your project and selecting New > Package. Note that a package doesn't really exist until you create some class or interface in that package. The more logical way to do this is to simply define a package when creating a new class. See creating new classes for more info about that. Once a new package is created (using either method), it will appear in the package explorer.

Once you've created some packages and some classes, you can also really easily move them around by dragging classes and packages around in the Package Explorer. For instance, you could make one package a sub-package of another by dragging it over the parent package like you would directories in your OS's file explorer. You can also move a class from one package to another by dragging it out of its current package and over the new package in the Package Explorer.