Java Reference
In-Depth Information
First, remember that p can hold the address of a Part object, not an object itself. The declaration simply allocates
storage for p but leaves it undefined. We can assign the null value to p , with this:
p = null;
We can also create a Part object and assign its address to p with this statement:
p = new Part("Air Filter", 8.75);
Now consider the following declaration:
Part[] part = new Part[5];
This declares an array called part with 5 elements. Since they are object variables, these elements are guaranteed
by Java to be set to null . As yet, no Part objects have been created. We can create objects and assign them individually
to each element of part , as follows:
part[0] = new Part("Air Filter", 8.75);
part[1] = new Part("Ball Joint", 29.95);
part[2] = new Part("Headlamp", 36.99);
part[3] = new Part("Spark Plug", 5.00);
part[4] = new Part("Disc Pads", 24.95);
The array part can now be pictured as shown in Figure 2-10 .
name: Air Filter
price: 8.75
name: Ball Joint
price: 29.95
part[0]
part[1]
part[2]
part[3]
part[4]
name: Headlamp
price: 36.99
name: Spark Plug
price: 5.00
name: Disc Pads
price: 24.95
Figure 2-10. An array of Part objects
Each element of part contains the address of the corresponding object.
Remember that, in general, each element of an array can be treated in the same way as a simple variable
of the array type. For instance, part[2] can be treated in the same way as p , above. And just as we can write
p.setPrice(40.00) , we can write part[2].setPrice(40.00) to change the price of Headlamp to 40.00 .
 
Search WWH ::




Custom Search