Java Reference
In-Depth Information
public class {
boolean x;
C
public class {
public static void main(String[] args) {
C c = new C();
System.out.println(
Test
private
public static void main(String[] args) {
C c = new C();
System.out.println(
c.x
);
System.out.println(
c.convert()
);
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 8.16 A n 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() {
}
8.9 Data Field Encapsulation
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 8.7 can be modified directly (e.g., c1.radius = 5 or
CircleWithStaticMembers.numberOfObjects = 10 ). This is not a good practice—for
two reasons:
VideoNote
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 ).
Second, the class becomes difficult to maintain and vulnerable to bugs. Suppose
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