Java Reference
In-Depth Information
The variable words is an array of references to String objects. The new operator
in the declaration instantiates the array and reserves space for five String refer-
ences. This declaration does not create any String objects; it merely creates an
array that holds references to String objects. Initially, the array looks like this:
words
After a few String objects are created and put in the array, it might look like this:
words
“friendship”
“loyalty”
“honor”
The words array is an object, and each character string it holds is its own object.
Each object contained in an array has to be instantiated separately.
Keep in mind that String objects can be represented as string literals. So the
following declaration creates an array called verbs and uses an initializer list to
populate it with several String objects, each instantiated using a string literal:
String[] verbs = {"play", "work", "eat", "sleep"};
The program called GradeRange shown in Listing 8.5 creates an array of Grade
objects, then prints them. The Grade objects are created using several new opera-
tors in the initialization list of the array.
The Grade class is shown in Listing 8.6. Each Grade object represents a let-
ter grade for a school course and includes a numerical lower bound. The values
for the grade name and lower bound can be set using the Grade constructor, or
using appropriate mutator methods. Accessor methods are also defined, as is a
toString method to return a string representation of the grade. The toString
method is automatically invoked when the grades are printed in the main method.
Let's look at another example. Listing 8.7 shows the Movies class, which
contains a main method that creates, modifies, and examines a DVD collection.
 
 
Search WWH ::




Custom Search