Java Reference
In-Depth Information
The class itself is a somewhat abstract concept. As explained so far, it has little
value until an instance of the class is created. When this class is instantiated with
the new operator, such as in
Test g1 = new Test (4, 5.1);
then the variable g1 holds a pointer to an “instance” of the class Test .InJavaa
pointer to an object is called a reference .Aslaid out in memory, g1 is just a 32-bit
value that tells the JVM where to find the data for that class instance, whereas
that data itself is considerably larger than 32 bits. Thus, g1 is (a reference to) an
object or an instance of the class Test .You can't do much with the class itself but
you can use the reference g1 . (More about references in the following sections.)
During the new operation, the JVM allocates memory for, among other things,
the data fields i and x of the class. This data is stored, along with other aspects
of the object, somewhere in memory. You can imagine that the JVM creates and
keeps track of a unique ID just for that instance of the class.
If we create another instance of the class
Test g2 = new Test (53, 34.3);
then another set of data is stored under a different unique ID. So there will be
two blocks of memory, one for each instance. One block of memory contains the
values 4 and 5.1 for the i and x variables, and the other block contains the values
53 and 34.3, respectively. Since the JVM keeps track of the unique IDs, the JVM
always knows which block of memory to look in to find the correct values for a
particular instance of Test .
When a program invokes the methods of an object, the JVM loads the unique
data for that object into the fields, and these values are used in the code for the
methods of that class. When it invokes the same methods for a different instance
of the same class, then that object's data is used in the code. We often refer to
objects in rather abstract or pictorial metaphors as if both the data and methods
were contained within each object. However, at the processor level it just comes
down to sets of data, unique to each object, shifting in and out of the method codes.
3.4.1 Object references
Java references differ considerably from C and C
memory pointers where the
programmer can access and manipulate pointers directly.
Pointers in C and C
++
:
hold the actual addresses of data in memory
can be cast to different data types
can be altered to point to other memory locations
AJava reference holds an indirect address of an object in the JVM and:
the actual memory value of the reference is hidden
reference values cannot be altered
references can only be recast to a superclass or subclass of that object, never to other
data types (see Chapter 4 for a discussion of superclasses and subclasses)
++
Search WWH ::




Custom Search