Java Reference
In-Depth Information
Further, suppose a user class contains these statements:
Part af = new Part("Air Filter", 8.75);
printPart(af);
and suppose the first statement assigns the address
4000
, say, to
af
. When
printPart
is called,
4000
is copied to
a temporary location and this location is passed to
printPart
where it becomes known as
p
, the name of the formal
parameter. Since the value of
p
is
4000
, in effect it has access to the original object. In this example, the method simply
prints the values of the instance variables. But it could also change them, if it wanted.
Consider the following method in the class
Part
, which adds
amount
to the price of a part:
public static void changePrice(Part p, double amount) {
p.price += amount;
}
The user class can add
1.50
to the price of the Air Filter with this call:
Part.changePrice(af, 1.50);
As indicated earlier, the parameter
p
has access to the original object. Any change made to the object pointed to
by
p
is, in fact, a change to the original object.
We emphasize that the method
cannot
change the
value
of the actual argument
af
(since it has no access to it),
but it
can
change the
object pointed to
by
af
.
In passing, note that we have used this example mainly for illustrative purposes. In practice, it would probably be
better to write an instance method to change the price of a
Part
object.
2.11 Array of Objects
In Java, a
String
is an object. Therefore, an array of
String
s is, in fact, an array of objects. However, a
String
is a
special kind of object in Java and, in some ways, is treated differently from other objects. For one thing, a
String
is
immutable
; we cannot change its value. For another, we think of a
String
as having one field—the characters in
the string—whereas a typical object will have several. For these reasons, we take a look at arrays of objects other
than
String
s.
Consider the class
Part
defined previously. The class contains two instance variables defined as follows:
public class Part {
private String name; // instance variable
private double price; // instance variable
// methods and static variables
} //end class Part
It is helpful to recall what happens when we declare a
Part
variable
p
as in the following:
Part p;
Search WWH ::
Custom Search