Java Reference
In-Depth Information
Look first at the code inside
ExtBook
. Because
ExtBook
extends
Book
, it has access to
the
protected
members of
Book
, even though
ExtBook
is in a different package. Thus, it
can access
title
,
author
, and
pubDate
directly, as it does in the accessor methods it creates
for those variables. However, in
ProtectDemo
, access to these variables is denied because
ProtectDemo
is not a subclass of
Book
. For example, if you remove the comment symbol
from the following line, the program will not compile.
Importing Packages
When you use a class from another package, you can fully qualify the name of the class
with the name of its package, as the preceding examples have done. However, such an ap-
proach could easily become tiresome and awkward, especially if the classes you are qual-
ifying are deeply nested in a package hierarchy. Since Java was invented by programmers
for programmers—and programmers don't like tedious constructs—it should come as no
surprise that a more convenient method exists for using the contents of packages: the
im-
port
statement. Using
import
you can bring one or more members of a package into view.
This allows you to use those members directly, without explicit package qualification.
Ask the Expert
Q
:
I know that C++ also includes an access specifier called
protected.
Is it similar to
Java's?
A
:
Similar, but not the same. In C++,
protected
creates a member that can be accessed
by subclasses but is otherwise private. In Java,
protected
creates a member that can
be accessed by any code within its package but only by subclasses outside of its
package. You need to be careful of this difference when porting code between C++
and Java.
Here is the general form of the
import
statement:
import
pkg.classname
;