Java Reference
In-Depth Information
any part of any class that is a continuation of the class hierarchy rooted in the class in which
the method or field is declared. It is best to think of the protected access specifier as giving
access to any object that is at least of the type in which the field or method is declared.
Packages, like classes, form a hierarchy that is a tree. But membership in a package is not
polymorphic; that is, something that is defined in the package is not part of
the foo or the package. Fields and methods that have package protection can be ac-
cessed only by things that are in exactly the same package. If there is a field or method that is
package protected in the package , don't expect to be able to access it in the package .
Classes and interfaces are also subject to access specifications. However, with the exception
of inner classes, the possible access specifications for these parts of the language are limited to
either package access (in which case the class or interface are not labeled) or public access. A
little thought convinces one that these are the only access specifiers that make sense. A class
or interface that can be called only by itself is not very interesting. Neither is one that can only
be called by subclasses. Although from a purely linguistic point of view, this lack of symmetry
may be troubling, the fact that the language keeps you from doing something useless more
than makes up for it.
You can also put some access specifications on the methods defined in an interface, but what
you do here doesn't really matter. Only two access specifiers are legal for interface methods.
You can mark an interface method as abstract , but doing so has no effect, since all interface
methods are unimplemented at the level of the interface and are instantiated only in classes
that implement the interface. Likewise, you can mark an interface method as public , but this
is documentation at best; an interface method is accessible to any code that can access the
interface. If the interface is marked as public , then all of the methods of that interface are
public , even if that access specifier does not preface the method declaration. If the interface
has only package visibility, then the methods in that interface will also have only package vis-
An Example
Let's go back to our baseball statistics system and apply some good practice with regard to
packages. We at least have a package declaration on all of our files (they are in the package
examples ), but it's hard to argue that the particular package name we chose is going to be
globally unique. So we should probably start by picking a prefix for the package that will give
us a higher confidence that the namespace for our system is unique. When I'm doing this at
Search WWH ::

Custom Search