Java Reference
In-Depth Information
16 numberOfObjects++;
17 }
18
19
/** Return radius */
20
public double
getRadius()
{
accessor method
21
return
radius;
22 }
23
24
/** Set a new radius */
25 {
26 radius = (newRadius >=
0
) ? newRadius :
0
;
27 }
28
29
public void
setRadius(
double
newRadius)
mutator method
/** Return numberOfObjects */
30
public static int
getNumberOfObjects()
{
accessor method
31
return
numberOfObjects;
32 }
33
34
/** Return the area of this circle */
35
public double
getArea() {
36
return
radius * radius * Math.PI;
37 }
38 }
The
getRadius()
method (lines 20-22) returns the radius, and the
setRadius(newRadius)
method (line 25-27) sets a new radius for the object. If the new radius is negative,
0
is set as the
radius for the object. Since these methods are the only ways to read and modify the radius, you
have total control over how the
radius
property is accessed. If you have to change the imple-
mentation of these methods, you don't need to change the client programs. This makes the class
easy to maintain.
Listing 8.10 gives a client program that uses the
Circle
class to create a
Circle
object
and modifies the radius using the
setRadius
method.
L
ISTING
8.10
TestCircleWithPrivateDataFields.java
1
public class
TestCircleWithPrivateDataFields {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Create a circle with radius 5.0
5 CircleWithPrivateDataFields myCircle =
6
new
CircleWithPrivateDataFields(
5.0
);
7 System.out.println(
"The area of the circle of radius "
8 +
myCircle.getRadius()
+
" is "
+
myCircle.getArea()
);
invoke public method
9
10
// Increase myCircle's radius by 10%
11 myCircle.setRadius(myCircle.getRadius() *
1.1
);
12 System.out.println(
"The area of the circle of radius "
13 +
myCircle.getRadius()
myCircle.getArea()
+
" is "
+
);
invoke public method
14
15 System.out.println(
"The number of objects created is "
16 +
CircleWithPrivateDataFields.getNumberOfObjects()
);
invoke public method
17 }
18 }
The data field
radius
is declared private. Private data can be accessed only within their
defining class, so you cannot use
myCircle.radius
in the client program. A compile error
would occur if you attempted to access private data from a client.