System, but they may not be reproduced for publication


part of that package’s namespace



Yüklə 83 Mb.
Pdf görüntüsü
səhifə38/82
tarix19.04.2023
ölçüsü83 Mb.
#106251
1   ...   34   35   36   37   38   39   40   41   ...   82
Java A Beginner’s Guide, Eighth Edition ( PDFDrive )


part of that package’s namespace.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
package called mypack:
Typically, Java uses the file system to manage packages, with each package stored in its
own directory, and this is the approach assumed by the discussions and examples of
packages in this book. For example, the .class files for any classes you declare to be
part of mypack must be stored in a directory called mypack.
Like the rest of Java, package names are case sensitive. This means that the directory in
which a package is stored must be precisely the same as the package name. If you have
trouble trying the examples in this chapter, remember to check your package and


directory names carefully. Lowercase is often used for package names.
More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong. It does not
exclude other classes in other files from being part of that same package. Most real­
world packages are spread across many files.
You can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled package
statement is shown here:
package pack1.pack2.pack3...packN;
Of course, you must create directories that support the package hierarchy that you
create. For example,
must be stored in .../alpha/beta/gamma, where ... specifies the path to the specified
directories.
Finding Packages and CLASSPATH
As just explained, packages are typically mirrored by directories. This raises an
important question: How does the Java run­time system know where to look for
packages that you create? As it relates to the examples in this chapter, the answer has
three parts. First, by default, the Java run­time system uses the current working
directory as its starting point. Thus, if your package is in a subdirectory of the current
directory, it will be found. Second, you can specify a directory path or paths by setting
the CLASSPATH environmental variable. Third, you can use the ­classpath option
with java and javac to specify the path to your classes. It is useful to point out that,
beginning with JDK 9, a package can be part of a module, and thus found on the
module path. However, a discussion of modules and module paths is deferred until
Chapter 15
. For now, we will use only class paths.
For example, assuming the following package specification:
In order for a program to find mypack, the program can be executed from a directory
immediately above mypack, or CLASSPATH must be set to include the path to


mypack, or the ­classpath option must specify the path to mypack when the
program is run via java.
The easiest way to try the examples shown in this chapter is to simply create the
package directories below your current development directory, put the .class files into
the appropriate directories, and then execute the programs from the development
directory. This is the approach used by the following examples.
One last point: To avoid problems, it is best to keep all .java and .class files associated
with a package in that package’s directory. Also, compile each file from the directory
above the package directory.
A Short Package Example
Keeping the preceding discussion in mind, try this short package example. It creates a
simple book database that is contained within a package called bookpack.


Call this file BookDemo.java and put it in a directory called bookpack.
Next, compile the file. You can do this by specifying
from the directory directly above bookpack. Then try executing the class, using the
following command line:


Remember, you will need to be in the directory above bookpack when you execute this
command. (Or, use one of the other two options described in the preceding section to
specify the path to bookpack.)
As explained, BookDemo and Book are now part of the package bookpack. This
means that BookDemo cannot be executed by itself. That is, you cannot use this
command line:
Instead, BookDemo must be qualified with its package name.
PACKAGES AND MEMBER ACCESS
The preceding chapters have introduced the fundamentals of access control, including
the private and public modifiers, but they have not told the entire story. One reason
for this is that packages also participate in Java’s access control mechanism, and this
aspect of access control had to wait until packages were covered. Before we continue, it
is important to note that the modules feature added by JDK 9 also offers another
dimension to accessibility, but here we focus strictly on the interplay between packages
and classes.
The visibility of an element is affected by its access specification—private, public,
protected, or default—and the package in which it resides. Thus, as it relates to classes
and packages, the visibility of an element is determined by its visibility within a class
and its visibility within a package. This multilayered approach to access control
supports a rich assortment of access privileges. 
Table 8­1
summarizes the various
access levels. Let’s examine each access option individually.


Table 8­1 Class Member Access
If a member of a class has no explicit access modifier, then it is visible within its
package but not outside its package. Therefore, you will use the default access
specification for elements that you want to keep private to a package but public within
that package.
Members explicitly declared public are the most visible, and can be accessed from
different classes and different packages. A private member is accessible only to the
other members of its class. A private member is unaffected by its membership in a
package. A member specified as protected is accessible within its package and to
subclasses in other packages.
Table 8­1
applies only to members of classes. A top­level class has only two possible
access levels: default and public. When a class is declared as public, it is accessible
outside its package. If a class has default access, it can be accessed only by other code
within its same package. Also, a class that is declared public must reside in a file by the
same name.
NOTE
Remember, the modules feature added by JDK 9 can also affect accessibility. Modules
are discussed in 
Chapter 15
.
A Package Access Example


In the package example shown earlier, both Book and BookDemo were in the same
package, so there was no problem with BookDemo using Book because the default
access privilege grants all members of the same package access. However, if Book were
in one package and BookDemo were in another, the situation would be different. In
this case, access to Book would be denied. To make Book available to other packages,
you must make three changes. First, Book needs to be declared public. This makes
Book visible outside of bookpack. Second, its constructor must be made public, and
finally, its show( ) method needs to be public. This allows them to be visible outside
of bookpack, too. Thus, to make Book usable by other packages, it must be recoded
as shown here:
To use Book from another package, either you must use the import statement
described in the next section, or you must fully qualify its name to include its full
package specification. For example, here is a class called UseBook, which is contained
in the bookpackext package. It fully qualifies Book in order to use it.


Notice how every use of Book is preceded with the bookpack qualifier. Without this
specification, Book would not be found when you tried to compile UseBook.
UNDERSTANDING PROTECTED MEMBERS
Newcomers to Java are sometimes confused by the meaning and use of protected. As
explained, the protected modifier creates a member that is accessible within its
package and to subclasses in other packages. Thus, a protected member is available
for all subclasses to use but is still protected from arbitrary access by code outside its
package.
To better understand the effects of protected, let’s work through an example. First,
change the Book class so that its instance variables are protected, as shown here:


Next, create a subclass of Book, called ExtBook, and a class called ProtectDemo
that uses ExtBook. ExtBook adds a field that stores the name of the publisher and
several accessor methods. Both of these classes will be in their own package called
bookpackext. They are shown here:



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
approach could easily become tiresome and awkward, especially if the classes you are
qualifying 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 import 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.
Here is the general form of the import statement:
import pkg.classname;
Here, pkg is the name of the package, which can include its full path, and classname is
the name of the class being imported. If you want to import the entire contents of a
package, use an asterisk (*) for the class name. Here are examples of both forms:
In the first case, the MyClass class is imported from mypack. In the second, all of the
classes in mypack are imported. In a Java source file, import statements occur
immediately following the package statement (if it exists) and before any class
definitions.
You can use import to bring the bookpack package into view so that the Book class
can be used without qualification. To do so, simply add this import statement to the
top of any file that uses Book.


For example, here is the UseBook class recoded to use import:
Notice that you no longer need to qualify Book with its package name.
JAVA’S CLASS LIBRARY IS CONTAINED IN
PACKAGES
As explained earlier in this book, Java defines a large number of standard classes that
are available to all programs. This class library is often referred to as the Java API
(Application Programming Interface). The Java API is stored in packages. At the top of
the package hierarchy is java. Descending from java are several subpackages. Here are
a few examples:


Since the beginning of this book, you have been using java.lang. It contains, among
several others, the System class, which you have been using when performing output
using println( ). The java.lang package is unique because it is imported
automatically into every Java program. This is why you did not have to import
java.lang in the preceding sample programs. However, you must explicitly import the
other packages. We will be examining several packages in subsequent chapters.
INTERFACES
In object­oriented programming, it is sometimes helpful to define what a class must do
but not how it will do it. You have already seen an example of this: the abstract method.
An abstract method defines the signature for a method but provides no
implementation. A subclass must provide its own implementation of each abstract
method defined by its superclass. Thus, an abstract method specifies the interface to
the method but not the implementation. While abstract classes and methods are useful,
it is possible to take this concept a step further. In Java, you can fully separate a class’
interface from its implementation by using the keyword interface.
An interface is syntactically similar to an abstract class, in that you can specify one or
more methods that have no body. Those methods must be implemented by a class in
order for their actions to be defined. Thus, an interface specifies what must be done,
but not how to do it. Once an interface is defined, any number of classes can implement
it. Also, one class can implement any number of interfaces.
To implement an interface, a class must provide bodies (implementations) for the
methods described by the interface. Each class is free to determine the details of its own
implementation. Two classes might implement the same interface in different ways, but
each class still supports the same set of methods. Thus, code that has knowledge of the
interface can use objects of either class since the interface to those objects is the same.
By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
Before continuing an important point needs to be made. JDK 8 added a feature to
interface that made a significant change to its capabilities. Prior to JDK 8, an interface
could not define any implementation whatsoever. Thus, prior to JDK 8, an interface
could define only what, but not how, as just described. JDK 8 changed this. Today, it is
possible to add a default implementation to an interface method. Furthermore, static
interface methods are now supported, and beginning with JDK 9, an interface can also
include private methods. Thus, it is now possible for interface to specify some


behavior. However, such methods constitute what are, in essence, special­use features,
and the original intent behind interface still remains. Therefore, as a general rule, you
will still often create and use interfaces in which no use is made of these new features.
For this reason, we will begin by discussing the interface in its traditional form. New
interface features are described at the end of this chapter.
Here is a simplified general form of a traditional interface:

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   34   35   36   37   38   39   40   41   ...   82




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə