packages, import, and API Example
Java provides many pre-defined classes that are available to programmers to use. They are referred to as the Java API (Application Programmers Interface);Each API class belongs to a named package, for example java.awt. The name starts with java or javax followed by a dot, then followed by another name like awt.
The class Color is in the package java.awt. Its full name is java.awt.Color and you must let the compiler know it if you want to use it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Packages Example
import java.awt.*;
import java.util.Date;
class Explainer {
public static void main(String[] args) {
Color c0 = Color.white;
java.awt.Color c1 = java.awt.Color.blue;
String s0 = "abc";
java.lang.String s1 = "123";
Date today = new Date();
}
}
2 The import declaration is one way of informing the compiler where to look for pre-compiled API classes, which it needs to know if any of them are used in the program.
This statement informs the compiler to look in the package named java.awt, anywhere (that's the purpose of *, it means any class in the package java.awt).
3 This import declaration consists of a package name java.util followed by a dot and then the class name Date. It informs the compiler specifically of the package for the pre-compiled API class java.util.Date.
If the statement had read import java.util.*; then the compiler would still have found the Date class.
But by being specific about the full name it avoided any possible ambiguity with a Date class defined elsewhere.
9-10 A benefit of using the import declaration is that it allows the programmer to refer to an API class by a short name, such as Color, rather than the full name java.awt.Color.
An example using the short name is shown in the first of these two lines.
In the second line, the full name (or in Java terminology, the fully qualified name) is used. This full name would have been required had the import declaration not been used.
12 The String class is part of the API and its full name java.lang.String is not referred to. How does the compiler find the class?
Java has a package java.lang that holds fundamental classes for programming, such as String and System, and is automatically imported. In each program it is as if import java.lang.*; is present.
This line shows a statement referring to String normally. The line below has a statement with the unnecessary full name.
15 When the compiler looks in the API for a class name such as Date it will ordinarily look first in the package java.lang and then, if it's not found, the places indicated by any import declarations.
If, on the other hand, the full name such as java.util.Date is used, the compiler need search no further. The full name informs the compiler of the precise whereabouts of the compiled Date class.
