Java Reference
In-Depth Information
}
}
This way, nobody can override the
checkPassword
method with another
method that simply returns
true
.
461
462
10.7 Access Control
Java has four levels of controlling access to fields, methods, and classes:
ȗ
public
access
ȗ
private
access
ȗ
protected
access (see
Advanced Topic 10.3
)
ȗ package access (the default, when no access modifier is given)
You have already used the
private
and
public
modifiers extensively. Private
features can be accessed only by the methods of their own class. Public features can
be accessed by methods of all classes. We will discuss protected access in
Advanced
Topic 10.3
Ȍwe will not need it in this topic.
A field or method that is not declared as
public
,
private
, or
protected
can
be accessed by all classes in the same package, which is usually not desirable.
If you do not supply an access control modifier, then the default is package access.
That is, all methods of classes in the same package can access the feature. For
example, if a class is declared as
public
, then all other classes in all packages can
use it. But if a class is declared without an access modifier, then only the other classes
in the same package can use it. Package access is a good default for classes, but it is
extremely unfortunate for fields. Instance and static fields of classes should always be
private
. There are a few exceptions:
ȗ Public constants (
public static final
fields) are useful and safe.
ȗ Some objects, such as
System.out
, need to be accessible to all programs and
therefore should be public.