Java Reference
In-Depth Information
public class
C {
private boolean
x;
public class
Test {
public static void
main(String[] args) {
C c =
new
C();
System.out.println(c.x);
System.out.println(c.convert());
}
}
public static void
main(String[] args) {
C c =
new
C();
System.out.println(c.x);
System.out.println(c.convert());
}
private int
convert() {
return
x ?
1
:
-1
;
}
}
(a) This is okay because object
c
is used inside the class
C
.
(b) This is wrong because
x
and
convert
are private in class
C
.
F
IGURE
9.16
An object can access its private members if it is defined in its own class.
Caution
The
private
modifier applies only to the members of a class. The
public
modifier
can apply to a class or members of a class. Using the modifiers
public
and
private
on local variables would cause a compile error.
Note
In most cases, the constructor should be public. However, if you want to prohibit the
user from creating an instance of a class, use a
private constructor
. For example, there
is no reason to create an instance from the
Math
class, because all of its data fields and
methods are static. To prevent the user from creating objects from the
Math
class, the
constructor in
java.lang.Math
is defined as follows:
private constructor
private
Math() {
}
Making data fields private protects data and makes the class easy to maintain.
Key
Point
The data fields
radius
and
numberOfObjects
in the
CircleWithStaticMembers
class in
Listing 9.6 can be modified directly (e.g.,
c1.radius = 5
or
CircleWithStaticMembers
.numberOfObjects = 10
). This is not a good practice—for two reasons:
Data field encapsulation
First, data may be tampered with. For example,
numberOfObjects
is to count the
number of objects created, but it may be mistakenly set to an arbitrary value (e.g.,
CircleWithStaticMembers.numberOfObjects = 10
).
■
VideoNote
Data field encapsulation
Second, the class becomes difficult to maintain and vulnerable to bugs. Sup-
pose you want to modify the
CircleWithStaticMembers
class to ensure that
the radius is nonnegative after other programs have already used the class. You
have to change not only the
CircleWithStaticMembers
class but also the
programs that use it, because the clients may have modified the radius directly
(e.g.,
c1.radius = -5
).
■
To prevent direct modifications of data fields, you should declare the data fields private,
using the
private
modifier. This is known as
data field encapsulation
.
data field encapsulation
Search WWH ::
Custom Search