Java Reference
In-Depth Information
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 9.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.
9.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
9.21
What are the benefits of data field encapsulation?
9.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 9.8
4 CircleWithPrivateDataFields myCircle =
new
5 CircleWithPrivateDataFields(
5.0
);
6
printCircle(myCircle);
pass an object
7 }
8
9
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.
The program in Listing 9.10 demonstrates the difference between passing a primitive type
value and passing a reference value.
pass-by-value
Search WWH ::
Custom Search