Java Reference
In-Depth Information
tory
package1
, although your IDE should help you do it.
The name of a package, like
package1
, as well as the placement of directo-
ry
package1
, must satisfy certain rules, which we will look at later.
The default package
Actually, you probably will not be using the package statement for some
time. The classes you write do not have a package statement, so they are auto-
matically placed in a “default” package and appear in the project directory for the
program you are writing. If you are using an IDE, various files produced by the
IDE are also in this directory, as well as the
.class
files that are produced when
classes are compiled.
But you need to know about packages so that you can use the
import state-
ment
, which we explain momentarily.
Referencing classes in other packages
Suppose we have a second class,
TwoClass
, which is in a file
TwoClass.java
and belongs in the default package, since it does not contain a
package statement. We put a method
m
in this class:
public class
TwoClass {
public void
m() {
OneClass d=
new
OneClass(); //
SYNTACTIC ERROR!
...
}
}
Generally, to refer to a class, one simply uses the class name, as in the two ref-
erences to
OneClass
in the initializing declaration of
d
above. However, since
class
OneClass
appears in a different package (package
package1
), all refer-
ences to it must be preceded by the name of the package. The rule is:
Package-reference rule
: A reference to a class that appears in
another, non-default, package, must be preceded by the name of
the package followed by a dot.
Example:
package1.OneClass d=
new
package1.OneClass();
The import statement
This package-reference rule makes referring to classes in other packages
cumbersome. But there is a way around it. If we import the class using a suitable
import statement
just before the class definition:
import
package1.OneClass;
we do not need to prefix a reference to the class with the package name.
A package may contain many classes, and to write an import statement for
each one can be a chore. Hence, Java provides an abbreviation. The statement
Search WWH ::
Custom Search