Java Reference
In-Depth Information
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.
Suppose you combined
TestCircleWithPrivateDataFields
and
Circle
into one class
by moving the
main
method in
TestCircleWithPrivateDataFields
into
Circle
. Could
you use
myCircle.radius
in the
main
method? See Checkpoint Question 8.22 for the answer.
Design Guide
To prevent data from being tampered with and to make the class easy to maintain,
declare data fields private.
8.20
✓
✓
What is an accessor method? What is a mutator method? What are the naming con-
ventions for accessor methods and mutator methods?
Check
Point
8.21
What are the benefits of data field encapsulation?
8.22
In the following code,
radius
is private in the
Circle
class, and
myCircle
is an
object of the
Circle
class. Does the highlighted code cause any problems? If so,
explain why.
public class
Circle {
private double
radius =
1
;
/** Find the area of this circle */
public double
getArea() {
return
radius * radius * Math.PI;
}
public static void
main(String[] args) {
Circle myCircle =
new
Circle();
System.out.println(
"Radius is "
+
myCircle.radius
);
}
}
Passing an object to a method is to pass the reference of the object.
Key
Point
You can pass objects to methods. Like passing an array, passing an object is actually passing
the reference of the object. The following code passes the
myCircle
object as an argument to
the
printCircle
method:
1
public class
Test {
2
public static void
main(String[] args) {
3
// CircleWithPrivateDataFields is defined in Listing 8.9
4 CircleWithPrivateDataFields myCircle =
new
5 CircleWithPrivateDataFields(
5.0
);
6
7 }
8
9
pass an object
printCircle(myCircle);
public static void
printCircle(CircleWithPrivateDataFields c)
{
10 System.out.println(
"The area of the circle of radius "
11 + c.getRadius() +
" is "
+ c.getArea());
12 }
13 }
Java uses exactly one mode of passing arguments: pass-by-value. In the preceding code,
the value of
myCircle
is passed to the
printCircle
method. This value is a reference to a
Circle
object.
pass-by-value