Java Reference
In-Depth Information
• Internal fields and methods that are visible outside the class just clutter up the
API. Keeping visible fields to a minimum keeps your class tidy and therefore
easier to use and understand.
• If a method is visible to the users of your class, you have to document it. Save
yourself time and effort by hiding it instead.
Access Control
Java defines access control rules that can restrict members of a class from being used
outside the class. In a number of examples in this chapter, you've seen the public
modifier used in field and method declarations. This public keyword, along with
protected and private (and one other, special one) are access control modiiers ;
they specify the access rules for the field or method.
Access to packages
Access control on a per-package basis is not directly part of the Java language.
Instead, access control is usually done at the level of classes and members of classes.
A package that has been loaded is always accessible to code
defined within the same package. Whether it is accessible to
code from other packages depends on the way the package is
deployed on the host system. When the class files that com‐
prise a package are stored in a directory, for example, a user
must have read access to the directory and the files within it in
order to have access to the package.
Access to classes
By default, top-level classes are accessible within the package in which they are
defined. However, if a top-level class is declared public , it is accessible everywhere.
In Chapter 4 , we'll meet nested classes. These are classes that
can be defined as members of other classes. Because these
inner classes are members of a class, they also obey the mem‐
ber access-control rules.
Access to members
The members of a class are always accessible within the body of the class. By default,
members are also accessible throughout the package in which the class is defined.
This default level of access is often called package access . It is only one of four possi‐
ble levels of access. The other three levels are defined by the public , protected , and
private modifiers. Here is some example code that uses these modifiers:
Search WWH ::

Custom Search