Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc. A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management
A package allows a developer to group classes (and interfaces) together. These classes will all be related in some way – they might all be to do with a specific application or perform a specific set of tasks. For example, the Java API is full of packages. One of them is the javax.xml package. It and its subpackages contain all the classes in the Java API to do with handling XML.
A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces
- Every class is part of some package.
- All classes in a file are part of the same package.
- You can specify the package using a package declaration:
package name ;
as the first (non-comment) line in the file. - Multiple files can specify the same package name.
- If no package is specified, the classes in the file go into a special unnamed package (the same unnamed package for all files).
- If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name).
- You can access public classes in another (named) package using: package-name.class-name You can access the public fields and methods of such classes using:
package-name.class-name.field-or-method-name
You can avoid having to include the package-name using:
import package-name.*;
For more tutorial see here.