Java Reference
In-Depth Information
if they don't extend this class). Classes in other packages (unless they extend
this class) can not get at such members.
A
public
data member or method may be accessed by any code in
any class.
What if you do not put an access specifier on? Then the item (data mem-
ber, method, or class) has package visibility. Such an item is accessible to any
other class within the package, but no further. Not even derived classes, unless
they are in the same package, are allowed to see it.
12
In terms of how restrictive the access is, you can think of the terms in order
of decreasing strictness as:
•
private
• (package)
13
•
protected
•
public
TIP
Beginner Java programmers often declare everything as
public
, so that they
can ignore such issues. But then they get the OO religion, and having experi-
enced reliability issues (others messing with their variables) they go to the other
extreme and declare
private
as much as possible. The problem here is that
they often don't know how others will want to reuse their code. Restricting every-
thing to
private
makes reuse more narrow. We prefer using
private
for
data members but
protected
for those internal helper methods that you might
otherwise make
private
; this hides your implementation from most other
classes while allowing someone to override your methods, effectively providing
a way for them to override your implementation. Allow those who would build
on your work the ability to do so without having to reimplement.
Here is a simple example of each type of declaration:
12. If you are a C++ programmer, the following description may mean something to you
(if not, skip this): All classes within a package are essentially “friends.”
13. Remember there is no keyword for package level protection, rather it is the absence of a
keyword that denotes this level of protection. We had to write something in that space on the
page so you'd know what we're talking about.