Objects and References
An Introduction with Examples in Java |
Prof. David Bernstein
|
Computer Science Department |
bernstdh@jmu.edu |
boolean
, double
,
int
,... that don't have constituent parts
null
:
null
can be used to indicate that
a reference variable does not refer to anything
main()
)
main()
)
new
operator is invokeString
literals
(i.e., it stores only one copy of a specific String
)
new
Operator and Memorylength
attribute
at that addressNote About the Heap, Literals space, and Class space: We will sometimes worry about the size of entities and work directly with the bytes and will sometimes work with larger entities and not worry about the bytes they occupy.
In this example (from a fragment of main()
), the same
memory is used for the variables during each iteration.
In this example (from a fragment of main()
), memory is
allocated for a Color
object each iteration. (Reminder:
A Color
object has three int
attributes,
named red
, green
, and
blue
.)
Note: In this example we are not worrying about the size of the three
int
attributes in the Color
objects.
final
Variablesfinal
Variables:
final
Consider the following class:
javaexamples/basics/Pair.java (Fragment: 0)
And the following fragment (in main()
):
The following example (from a fragment of main()
) uses
the assignment operator both during the instantiation of an object
and to create an alias.
In the following example (from a fragment
of main()
), p
and q
refer to
the same object so changing the attributes of one changes the
attributes of "the other".
The relational equals operator (i.e., ==
) can be used
with reference types, and it is sometimes necessary to do so, but you must
understand that it compares two references.
==
operator compares references.equals()
method for this purposeString
Literals
String
literals are reference types, but the compiler
can be smart and store only one instance of each (a process called
"interning").
String
"
Since String
objects are reference types, a String
variable can contain the reference null
.
This is not the same thing as what is sometimes called the
"null String
" (and sometimes, perhaps less ambiguously, called
the "empty String
").
Consider the following example:
and recall that the Math
class has two static
double
attributes, E
and PI
.
Note that the address of c
changes every iteration. Hence
the memory that was allocated in the previous iteration becomes garbage.
int[] scores;
scores = new int[3];
scores[0] = 5;
Student[] cs149;
cs149 = new Student[3];
cs149[0] = new Student("Barney","Rubble");