Java Reference
In-Depth Information
and some say they are. But, all authorities agree that the arrays themselves are objects.
Given that arrays are objects, it seems that one should view array types as classes, and
we will do so. However, although an array type double[] is a class, the syntax for
creating an array object is a bit different. To create an array, use the following syntax:
double [] a = new double [10];
You can view the expression new double[10] as an invocation of a constructor that
uses a nonstandard syntax. (The nonstandard syntax was used to be consistent with the
syntax used for arrays in older programming languages.)
As we have already seen, every array has an instance variable named length , which
is a good example of viewing an array as an object. As with any other class type, array
variables contain memory addresses, or, as they are usually called in Java, references . So,
array types are reference types. 3
Since an array is an object, you might be tempted to think of the indexed variables
of an array, such as a[0] , a[1] , and so forth, as being instance variables of the object.
This is actually a pretty good analogy, but it is not literally true. Indexed variables
are not instance variables of the array. Indexed variables are a special kind of variable
peculiar to arrays. The only instance variable in an array is the length instance variable.
An array object is a collection of items of the base type. Viewed as such, an array
is an object that can be assigned with the assignment operator and plugged in for a
parameter of an array type. Because an array type is a reference type, the behaviors of
arrays with respect to assignment = , == , and parameter passing mechanisms are the
same as what we have already described for classes. In the next few subsections, we
discuss these details about arrays.
Arrays Are Objects
In Java, arrays are considered to be objects, and, although there is some disagreement on
this point, you can safely view an array type as a class type.
Array Types Reference Types
A variable of an array type holds the address of where the array object is stored in memory.
This memory address is called a reference to the array object.
3 In many programming languages, such as C++, arrays are also reference types just as they are in Java.
So, this detail about arrays is not peculiar to Java.
 
Search WWH ::




Custom Search