Examine Packages and the Role they play in Java Class Organization.
The Role of Packages in Java Class Organization
To aid in the organization of classes, Java provides a construct known as a package that is used to organize classes into functionally-related groups. Packages do not directly impact the internal makeup of a class but they do impact the relationship between classes.
All of the classes in the Java API are organized into a group of packages.
The standard java.lang package is the only package that is automatically imported into every Java program.
Packages help you uniquely identify classes. The package to which a class belongs is implicitly part of the class name. So the standard Java class Graphic is really named java.awt.Graphics. This identification helps to provide structure to all Java classes.
Package Guidelines
Below are some guidelines for package naming and structuring: Follow these java package naming conventions:
Structure your packages according to their functional role as well as their business role
Break down your packages according to their functionality or modules. for example com.course.module.lesson
Do not created too many packages if you have fewer classes in the package
Avoid going overboard with structuring, avoid separate packaging for exceptions, factories, etc. unless you have to .
If your project is small, keep it simple with few packages. e.g. com.course.module.lesson1 and com.course.module.lesson2
Consider build and distribution when naming ( this will allow you to distribute your api or SDK in a different package, see servlet api)
Defining Classes in Package using the package statement
You can define which classes and interfaces are in a package by using the package statement as the first statement in your class or interface.
Here is an example:
package certification;
class ExamQuestion {
// variables and mehods go here
}
The class in the previous code defines an ExamQuestion class in the certification package. You can define an interface, MultipleChoice, in a similar manner:
The diagram figure 2-2: shows the UML representation of the package certification, with the class ExamQuestion and the interface MultipleChoice.
The name of the package in the previous examples is certification. You may use such names for small projects that contain only a few classes and interfaces, but it is common for organizations to use subpackages to define all their classes.
For example, if people at Oracle define a class to store exam questions for a Java Associate exam, they might use the package name com.oracle .javacert.associate. Figure 2-3 shows its UML representation, together with the corresponding class definition: