AP Computer Science/Packages and Classes
This will provide a basic overview of the usage of packages and classes in the Java programming language.
Packages and ClassesEdit
A class groups together the related code belonging to a single program. A class is generally made of a group of methods, or groups of code that tell the computer what to do when they are called, or used. Classes can be related to each other and be used with each other, but some classes can stand alone. Java provides many classes that are created in advance, but the typical Java program relies on user-defined classes. These classes have objects, which interact with each other and those from Java class libraries.
Related Java classes are grouped together into packages. Many packages are provided with the Java compiler, which turns the code into executable programs. You can put your classes together into your own package, but this will not be tested on the exam.
The package java.lang contains the most commonly used classes in Java programming, and is automatically provided to all programs. If you need to use any other classes, you must import them into you program by placing an import statement in your program. For example, to import a class called ClassName from a package called packagename, use the following import statement:
Java has a hierarchy of packages and subpackages which are smaller groups of classes grouped together in a package. Sometimes you will need to import a class from within a subpackage. To import a class called ClassName from subpackage called subpackagename from a package called packagename, use the following import statement:
If you want to import every class or most classes in a single package, there is no need to make a long list of import statements! Instead, you can simply import every class in a package using a simple import statement by using the asterisk or * in the statement. For example, to import every class in the package packagename, use the following import statement:
This does not, however, import any subpackage included in the package, or any class included in the subpackages! To import all of the classes in a subpackage called subpackagename from a package called packagename, use the following import statement:
The import statement allows you to use the objects and methods defined within the packages and/or classes that are imported. While you will neither be required to know about packages nor write import statements on the exam, it is important to know about them and how to use them when you practice writing code because unlike the AP exam, your computer will not import any required packages for you!