Java Reference
In-Depth Information
A private data field cannot be accessed by an object from outside the class that defines the
private field. However, a client often needs to retrieve and modify a data field. To make a pri-
vate data field accessible, provide a
get
method to return its value. To enable a private data
field to be updated, provide a
set
method to set a new value.
Note
Colloquially, a
get
method is referred to as a
getter
(or
accessor
), and a
set
method is
referred to as a
setter
(or
mutator
).
getter (or accessor)
setter (or mutator)
A
get
method has the following signature:
public
returnType getPropertyName()
boolean accessor
If the
returnType
is
boolean
, the
get
method should be defined as follows by convention:
public boolean
isPropertyName()
A
set
method has the following signature:
public void
setPropertyName(dataType propertyValue)
Let's create a new circle class with a private data-field radius and its associated accessor and
mutator methods. The class diagram is shown in Figure 8.17. The new circle class, named
CircleWithPrivateDataFields
, is defined in Listing 8.9:
Circle
-radius: double
-numberOfObjects: int
The - sign indicates
a private modifier
The radius of this circle (default: 1.0).
The number of circle objects created.
+Circle()
Constructs a default circle object.
+Circle(radius: double)
Constructs a circle object with the specified radius.
+getRadius(): double
Returns the radius of this circle.
+setRadius(radius: double): void
Sets a new radius for this circle.
+getNumberOfObjects(): int
Returns the number of circle objects created.
+getArea(): double
Returns the area of this circle.
F
IGURE
8.17
The
Circle
class encapsulates circle properties and provides get/set and other methods.
L
ISTING
8.9
CircleWithPrivateDataFields.java
1
public class
CircleWithPrivateDataFields {
2
/** The radius of the circle */
encapsulate
radius
private double
radius =
1
;
3
4
5
/** The number of objects created */
6
7
8
/** Construct a circle with radius 1 */
9
public
CircleWithPrivateDataFields() {
10 numberOfObjects++;
11 }
12
13
/** Construct a circle with a specified radius */
14
public
CircleWithPrivateDataFields(
double
newRadius) {
15 radius = newRadius;
private static int
numberOfObjects =
0
;
encapsulate
numberOfObjects