Java Reference
In-Depth Information
Table 3-1. Class member accessibility
Member visibility
Accessible to
Public
Protected
Default
Private
Deining class
Yes
Yes
Yes
Yes
Class in same package
Yes
Yes
Yes
No
Subclass in diferent package
Yes
Yes
No
No
Yes
No
No
No
Nonsubclass diferent package
Here are some simple rules of thumb for using visibility modifiers:
• Use
public
only for methods and constants that form part of the public API of
the class. The only acceptable usage of
public
fields is for constants or immut‐
able objects, and they must be also declared
final
.
• Use
protected
for fields and methods that aren't required by most program‐
mers using the class but that may be of interest to anyone creating a subclass as
part of a different package.
protected
members are technically part of the exported API
of a class. They must be documented and cannot be changed
without potentially breaking code that relies on them.
• Use the default package visibility for fields and methods that are internal imple‐
mentation details but are used by cooperating classes in the same package.
• Use
private
for fields and methods that are used only inside the class and
should be hidden everywhere else.
If you are not sure whether to use
protected
, package, or
private
accessibility, start
with
private
. If this is overly restrictive, you can always relax the access restrictions
slightly (or provide accessor methods, in the case of fields).
This is especially important when designing APIs because increasing access restric‐
tions is not a backward-compatible change and can break code that relies on access
to those members.
Data Accessor Methods
In the
Circle
example, we declared the circle radius to be a
public
field. The
Cir
cle
class is one in which it may well be reasonable to keep that field publicly