How to Access Members of a Class

Members (or elements) of an array are accessed by using the [] operator. The following accesses the ith member of the interger array X:
int x = X[i];
Members (fields) of objects are accessed using the . operator as follows:
int lat = NavStn.lat; //access latitude of a navigation station
int lng = NavStn.lng; //access its longitude also
where NavStn is an object reference pointing to an instance of the class of objects called NavStns{ }.

Members of the class itself - ie fields which pertain to the class as a whole rather than to individual objects of that class - are accessed in the same way. But, this time you use the class name instead of an object reference:

int NumStns = NavStns.NumStns; /*access the number of navigation
                                 stations currently on file */
Methods are also members of classes. Consequently they are accessed in the same way. The following example finds a station's current bearing:
int brg = NavStns.GetBrg(lat, lng);
Exceptions: If you access an object or array with a reference whose value happens to be null, then a NullPointerException is thrown. If you specify an array element number which is out of range (eg you ask for the 23rd element of an array which has only 16 elements), then an IndexOutOfBoundException is thrown. Java omits this check if at compile time it can be determined that the index cannot ever go out of range (eg in a loop of defined limits).
This page's parent within this Web Site. About this Web Site. Its home page. Email its Author.