Java Reference
In-Depth Information
false
. You can specify your own initial value for a primitive-type variable by assigning the
variable a value in its declaration, as in
private int
numberOfStudents =
10
;
Programs use variables of reference types (normally called
references
) to store the
addresses
of objects in the computer's memory. Such a variable is said to
refer to an object
in the program.
Objects
that are referenced may each contain
many
instance variables. Line
10 of Fig. 3.2:
Scanner input =
new
Scanner(System.in);
creates an object of class
Scanner
, then assigns to the variable
input
a
reference
to that
Scanner
object. Line 13 of Fig. 3.2:
Account myAccount =
new
Account();
creates an object of class
Account
, then assigns to the variable
myAccount
a
reference
to that
Account
object.
Reference-type instance variables, if not explicitly initialized, are initialized
by default to the value
null
—which represents a “reference to nothing.” That's why the
first call to
getName
in line 16 of Fig. 3.2 returns
null
—the value of
name
has
not
yet been
set, so the
default
initial value
null
is returned.
To call methods on an object, you need a reference to the object. In Fig. 3.2, the state-
ments in method
main
use the variable
myAccount
to call methods
getName
(lines 16 and
26) and
setName
(line 21) to interact with the
Account
object. Primitive-type variables do
not
refer to objects, so such variables
cannot
be used to call methods.
As mentioned in Section 3.2, when an object of class
Account
(Fig. 3.1) is created, its
String
instance variable
name
is initialized to
null
by
default
. But what if you want to pro-
vide a name when you
create
an
Account
object?
Each class you declare can optionally provide a
constructor
with parameters that can
be used to initialize an object of a class when the object is created. Java
requires
a con-
structor call for
every
object that's created, so this is the ideal point to initialize an object's
instance variables. The next example enhances class
Account
(Fig. 3.5) with a constructor
that can receive a name and use it to initialize instance variable
name
when an
Account
object is created (Fig. 3.6).
Initialization
When you declare a class, you can provide your own constructor to specify
custom initial-
ization
for objects of your class. For example, you might want to specify a name for an
Ac-
count
object when the object is created, as in line 10 of Fig. 3.6:
Account account1 =
new
Account(
"Jane Green"
);
In this case, the
String
argument
"Jane
Green"
is passed to the
Account
object's construc-
tor and used to initialize the
name
instance variable. The preceding statement requires that
the class provide a constructor that takes only a
String
parameter. Figure 3.5 contains a
modified
Account
class with such a constructor.