Imports, Packages & the Classpath
When you are writing a large Java program you can run into the problem of a cluttered name-space. This means that you are running out of fresh names for your classes.
Packages
A Java package is a collection of related classes.
- The full name of a Java class if of the form
package.class
. - Packages can be nested.
- Packages from the “standard lib” start with
java
orjavax
.
Example
The System
class is in package java.lang
. So it’s full name is java.lang.System
.
Import
The import
statement introduces a class to the current name-space.
The use java.util.Scanner
to get user input we can tell the compiler to include that class at the top of a source file:
import java.util.Scanner.
This is a convenience. Instead, without importing it, we cal still refer to java.util.Scanner
by its full name.
Apropos Convenience
The java.lang
package is automatically available to all classes without using the import
statement. This is why we could refer directly to System
and write:
System.out.println("Hello World");
instead of having to use its full package name:
java.lang.System.out.println("Hello World");
Creating Packages
To assign a class to a package, we need to do two things:
-
Add a package statement to the source code:
package mypackage;
Classes without this live in an unnamed default package.
-
Move the source file into a directory
mypackage/
Both compiler and interpreter will look forclass
files in a directory names just like their package.
Packages are not required for the assignments.
Classpath
This is a list of directories from which packages are looked up.
javac
andjava
both have command-line arguments to set the classpath.- The current directory is automatically added.
- You can use the environment-variables to set the classpath. (
CLASSPATH
on Linux).
Conventions
- Package names are usually all lower case to avoid conflict with class names.
- It is common to use reversed domain names for packages.
- Yields globally unique package names.
- Avoids naming collisions between libraries from different sources.
org.w3c.dom