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 private data field accessible, provide a
getter
method to return its value. To enable a private
data field to be updated, provide a
setter
method to set a new value. A getter method is also
referred to as an
accessor
and a setter to a
mutator
.
A getter method has the following signature:
getter (or accessor)
setter (or mutator)
public
returnType get
PropertyName
()
If the
returnType
is
boolean
, the getter method should be defined as follows by convention:
boolean accessor
public boolean
is
PropertyName
()
A setter method has the following signature:
public void
set
PropertyName
(
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Ā 9.17. The new circle class, named
CircleWithPrivateDataFields
, is defined in Listing 9.8:
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
9.17
The
Circle
class encapsulates circle properties and provides getter/setter and other methods.
L
ISTING
9.8
CircleWithPrivateDataFields.java
1
public class
CircleWithPrivateDataFields {
2
/** The radius of the circle */
3
private double
radius =
1
;
encapsulate
radius
4
5
/** The number of objects created */
6
private static int
numberOfObjects =
0
;
encapsulate
numberOfObjects
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;
16 numberOfObjects++;
Search WWH ::
Custom Search