Java Reference
In-Depth Information
basics of objects and references
2.2
In Java, an object is an instance of any of the nonprimitive types. Objects are
treated differently from primitive types. Primitive types, as already shown, are
handled by value , meaning that the values assumed by the primitive variables
are stored in those variables and copied from primitive variable to primitive
variable during assignments. As shown in Section 2.1, reference variables
store references to objects. The actual object is stored somewhere in memory,
and the reference variable stores the object's memory address. Thus a refer-
ence variable simply represents a name for that part of memory. This means
that primitive variables and reference variables behave differently. This sec-
tion examines these differences in more detail and illustrates the operations
that are allowed for reference variables.
In Java, an object is
an instance of any
of the nonprimitive
types.
2.2.1 the dot operator ( . )
The dot operator ( . ) is used to select a method that is applied to an object. For
instance, suppose we have an object of type Circle that defines an area
method. If theCircle references a Circle , then we can compute the area of the
referenced Circle (and save it to a variable of type double ) by doing this:
double theArea = theCircle.area( );
It is possible that theCircle stores the null reference. In this case, applying the
dot operator will generate a NullPointerException when the program runs.
Generally, this will cause abnormal termination.
The dot operator can also be used to access individual components of
an object, provided arrangements have been made to allow internal com-
ponents to be viewable. Chapter 3 discusses how these arrangements are
made. Chapter 3 also explains why it is generally preferable to not allow
direct access of individual components.
2.2.2 declaration of objects
We have already seen the syntax for declaring primitive variables. For objects,
there is an important difference. When we declare a reference variable, we are
simply providing a name that can be used to reference an object that is stored in
memory. However, the declaration by itself does not provide that object. For
example, suppose there is an object of type Button that we want to add into an
existing Panel p , using the method add (all this is provided in the Java library).
Consider the statements
 
 
Search WWH ::




Custom Search