Читайте также: |
|
A package is a kind of a class library which groups classes having similar functionality: input-output operations, network applications, and so on.
Each class belongs to some package.
Classes compiled with package declaration package... belong to the declared package.
Classes compiled without any package declaration belong to the default (unnamed) package.
Packages have hierarchical structure:
aPackage
aSubPackage
aSubPackage
For example, the package java.awt contains the subpackage java.awt.event.
Hierarchical structure of packages is mapped into directory structure (the consecutive levels of directories in the directory hierarchy correspond to consecutive levels in package hierarchy).
Why use packages?
Consider an example:
class A {
Button b = new Button("Ok"); // new object of the class Button
....
}
Two cases are possible:
In the first case the compiler (and the Java virtual machine) may find the class.
In the second case arises the problem: where to search for the class?
Moreover, use of the name Button may be ambiguous (is it the Button from the current directory or from somewhere else?).
Thus, packages group classes into namespaces and protect against the name conflicts.
Qualified names
A qualified name of a class (type) belonging to a named package has a form:
package_name.class_name
for example: java.awt.Button
class A {
java.awt.Button b = new java.awt.Button("Ok");
....
}
For the classes defined in the default (unnamed) package the qualified name is the same as the name of a class (for example: Pair).
In general, all class names used in a program should be qualified.
Fortunately, the import statement allows using simple names.
import java.awt.Button; // imports the name of the class java.awt.Button
class A {
java.awt.Frame f = new java.awt.Frame("Title");
Button b = new Button("Ok"); // use of the simple name of the class java.awt.Button
....
}
Because the name of the class java.awt.Button was imported, we may use its simplified name in the program. But the name of the class java.awt.Frame was not imported, so we must use its fully qualified name.
To import all the class names from a given package we must use an asterisk:
import java.awt.*; // imports all the class names from the package java.awt
class A {
Frame f = new Frame("Title"); // now the simplified name may be used
Button b = new Button("Ok");
....
}
The classes String and System used frequently in programs are in the package java.lang.
The package java.lang does not require the import statement.
The classes from this package are imported automatically.
Дата добавления: 2015-11-16; просмотров: 68 | Нарушение авторских прав
<== предыдущая страница | | | следующая страница ==> |
Static members | | | Scope of an identifier. Local variables. Access control. |