2.1. Introduction¶
In Java, a package allows you to organize classes that have related functionality. Proper code organization becomes increasingly important as the size of the project increases.
More formally, 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 [1].
When a class is contained within a package, its fully qualified name (or FQN for short) consists of two parts: the name of the package followed by the class name (sometimes referred to as the simple class name to differentiate it from the FQN). By convention, the simple class name will always begin with a capital letter.
For example, you have likely used the Scanner
class in the past. You may also remember
importing java.util.Scanner
at the top of some of your programs. Here, the simple
class name is Scanner
and its package is java.util
.
Note
When you import a class, you have to use its FQN, but once the class is imported, you can use its simple class name.
The two primary benefits of packages are:
Name Space Management:
Packages allow you to give a common name to a group of related types. For example,
java.util.Scanner
andjava.util.Random
are two utility classes provided in thejava.util
package. You and other programmers can easily determine that these types are related based on their package. They are both utilities that you have probably used in your code.Note
You could have two types with the same simple name that are located in different packages. For example, you could have a
java.util.Random
class and aedu.cs.uga.Random
class. Both classes have the same simple class name (Random
) but they can be differentiated by their package names.Access Protection:
Visibility in Java is not limited to
public
andprivate
. Packages and additional visibility modifiers enable programmers to declare things as visible only within a package.
In this chapter, you will create multiple classes, group them into a package, then compile and run them. The expectation is that you will follow along with this tutorial in a terminal emulator on Odin or some Unix machine. You should ask questions on Piazza if you are unable to proceed or if some aspect of the tutorial is particularly confusing.
Quick Review Questions
Given the FQN
java.lang.Math
, what is the simple class name and package name?Given the FQN
javafx.scene.control.Button
, what is the simple class name and package name?What are the two primary benefits of using packages in Java?
Quick Review Answers (Don’t open until you complete the questions above)p
The simple class name is
Math
and the package name isjava.lang
.The simple class name is
Button
and the package name isjavafx.scene.control
.Name space management and access protection.