Java Reference
In-Depth Information
17 }
18
19
/** Return radius */
accessor method
20
public double getRadius() {
21
return radius;
22 }
23
24 /** Set a new radius */
25 public void setRadius( double newRadius) {
26 radius = (newRadius >= 0 ) ? newRadius : 0 ;
27 }
28
29
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
implementation of these methods, you don't need to change the client programs. This makes
the class easy to maintain.
Listing 9.9 gives a client program that uses the Circle class to create a Circle object and
modifies the radius using the setRadius method.
L ISTING 9.9
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());
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() + " is " + myCircle.getArea());
14
15 System.out.println( "The number of objects created is "
16 + CircleWithPrivateDataFields.getNumberOfObjects());
17 }
18 }
invoke public method
invoke public method
invoke public method
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.
Since numberOfObjects is private, it cannot be modified. This prevents tampering. For
example, the user cannot set numberOfObjects to 100 . The only way to make it 100 is to
create 100 objects of the Circle class.
 
 
Search WWH ::




Custom Search