Java Reference
In-Depth Information
ȗ Very occasionally, several classes in a package must collaborate very closely.
In that case, it may make sense to give some fields package access. But inner
classes are usually a better solutionȌyou have seen examples in
Chapter 9
.
It is a common error to forget the keyword
private
, thereby opening up a potential
security hole. For example, at the time of this writing, the
Window
class in the
java.awt
package contained the following declaration:
public class Window extends Container
{
String warningString;
. . .
}
The programmer was careless and didn't make the field private. There actually was no
good reason to grant package access to the
warningString
fieldȌno other class
accesses it. It is a security risk. Packages are not closed entitiesȌany programmer
can make a new class, add it to the
java.awt
package, and gain access to the
warningString
fields of all
Window
objects! (Actually, this possibility bothered
the Java implementors so much that recent versions of the virtual machine refuse to
load unknown classes whose package name starts with Ȓ
java
.ȓ. Your own packages,
however, do not enjoy this protection.)
462
463
Package access for fields is rarely useful, and most fields are given package access by
accident because the programmer simply forgot the
private
keyword.
Methods should generally be
public
or
private
. We recommend avoiding the
use of package-visible methods.
Classes and interfaces can have public or package access. Classes that are generally
useful should have public access. Classes that are used for implementation reasons
should have package access. You can hide them even better by turning them into
inner classes; you saw examples of inner classes in
Chapter 9
. There are a few
examples of public inner classes, such as the
Ellipse2D.Double
class that you
saw in
Chapter 2
(
Section 2.13
). However, in general, inner classes should not be
public.