Java Reference
In-Depth Information
public
class
Laundromat
{
// People can use this class.
private
Laundry
[]
dirty
;
// They cannot use this internal field,
public
void
wash
()
{
...
}
// but they can use these public methods
public
void
dry
()
{
...
}
// to manipulate the internal field.
// A subclass might want to tweak this field
protected
int
temperature
;
}
These access rules apply to members of a class:
• All the fields and methods of a class can always be used within the body of the
class itself.
• If a member of a class is declared with the
public
modifier, it means that the
member is accessible anywhere the containing class is accessible. This is the
least restrictive type of access control.
• If a member of a class is declared
private
, the member is never accessible,
except within the class itself. This is the most restrictive type of access control.
• If a member of a class is declared
protected
, it is accessible to all classes within
the package (the same as the default package accessibility) and also accessible
within the body of any subclass of the class, regardless of the package in which
that subclass is defined.
• If a member of a class is not declared with any of these modifiers, it has
default
access (sometimes called
package
access) and it is accessible to code within all
classes that are defined in the same package but inaccessible outside of the
package.
m
g
O
Default access is
more
restrictive than
protected
—as default
access does not allow access by subclasses outside the package.
protected
access requires more elaboration. Suppose class
A
declares a
protected
field
x
and is extended by a class
B
, which is defined in a different package (this last
point is important). Class
B
inherits the
protected
field
x
, and its code can access
that field in the current instance of
B
or in any other instances of
B
that the code can
refer to. This does not mean, however, that the code of class
B
can start reading the
protected fields of arbitrary instances of
A
.
Let's look at this language detail in code. Here's the definition for
A
:
package
javanut6
.
ch03
;
public
class
A
{
protected
final
String
name
;