Java Reference
In-Depth Information
Instantiating an Object
In Java, the new keyword is used to instantiate an object. The new operator cre-
ates the object in memory and returns a reference to the newly created object.
This object will remain in memory as long as your program retains a reference
to the object.
The following statements declare an Employee reference and use the new
keyword to assign the reference to a new Employee object.
Employee e;
e = new Employee();
The reference e is pointing to the Employee object in memory. The new oper-
ator allocates memory for the object and then “zeroes” the memory so that
none of the object's fields will contain garbage. Instead, all fields will have an
initial value of zero. Table 4.1 shows what the initial value of a field will be,
depending on its data type.
When I first teach students about instantiating objects, I like to declare a ref-
erence first and then use the new keyword in a second statement to assign the
reference to a new object. This emphasizes the important fact that two entities
are being created in memory: the reference and the object. In the preceding
statements, e is declared as a reference to an Employee, meaning that e can
refer to any Employee object. In the second statement, e is then assigned to a
new Employee object.
Table 4.1
Initial Value of an Object's Fields
FIELD DATA TYPE
INITIAL VALUE
byte
0
short
0
int
0
long
0
float
0.0
double
0.0
char
the null character
boolean
false
reference of any type
null
Search WWH ::




Custom Search