Java Reference
In-Depth Information
Use the
private
modifier to hide the members of the class completely so that they cannot
be accessed directly from outside the class. Use no modifiers (the default) in order to allow
the members of the class to be accessed directly from any class within the same package but
not from other packages. Use the
protected
modifier to enable the members of the class to
be accessed by the subclasses in any package or classes in the same package. Use the
public
modifier to enable the members of the class to be accessed by any class.
T
ABLE
11.2
Data and Methods Visi
bility
Modifier
on members
in a class
Accessed
from the
same class
Accessed
from the
same package
Accessed from
a subclass in a
different package
Accessed
from a different
package
public
✓
✓
✓
✓
protected
-
✓
✓
✓
-
-
default (no modifier)
✓
✓
-
-
-
private
✓
package
p1
;
public class
C1 {
public int
x;
protected int
y;
int
z;
private int
u;
public class
C2 {
C1 o =
new
C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
protected void
m() {
}
can invoke o.m();
}
}
package
p2;
public class
C3
extends
C1 {
can access x;
can access y;
can access z;
cannot access u;
public class
C4
extends
C1 {
can access x;
can access y;
cannot access z;
cannot access u;
public class
C5 {
C1 o =
new
C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
can invoke m();
can invoke m();
cannot invoke o.m();
}
}
}
F
IGURE
11.5
Visibility modifiers are used to control how data and methods are accessed.
Your class can be used in two ways: (1) for creating instances of the class and (2) for defin-
ing subclasses by extending the class. Make the members
private
if they are not intended
for use from outside the class. Make the members
public
if they are intended for the users of
the class. Make the fields or methods
protected
if they are intended for the extenders of the
class but not for the users of the class.
The
private
and
protected
modifiers can be used only for members of the class.
The
public
modifier and the default modifier (i.e., no modifier) can be used on members of
the class as well as on the class. A class with no modifier (i.e., not a public class) is not acces-
sible by classes from other packages.
Search WWH ::
Custom Search