Java Reference
In-Depth Information
An object's data and methods can be accessed through the dot (
.
) operator via the
object's reference variable.
Key
Point
Newly created objects are allocated in the memory. They can be accessed via reference
variables.
9.5.1 Reference Variables and Reference Types
Objects are accessed via the object's
reference variables
, which contain references to the
objects. Such variables are declared using the following syntax:
reference variable
ClassName objectRefVar;
A class is essentially a programmer-defined type. A class is a
reference type
, which means
that a variable of the class type can reference an instance of the class. The following statement
declares the variable
myCircle
to be of the
Circle
type:
reference type
Circle myCircle;
The variable
myCircle
can reference a
Circle
object. The next statement creates an object
and assigns its reference to
myCircle
:
myCircle =
new
Circle();
You can write a single statement that combines the declaration of an object reference variable,
the creation of an object, and the assigning of an object reference to the variable with the fol-
lowing syntax:
ClassName objectRefVar =
new
ClassName();
Here is an example:
Circle myCircle =
new
Circle();
The variable
myCircle
holds a reference to a
Circle
object.
Note
An object reference variable that appears to hold an object actually contains a reference
to that object. Strictly speaking, an object reference variable and an object are different,
but most of the time the distinction can be ignored. Therefore, it is fine, for simplicity, to
say that
myCircle
is a
Circle
object rather than use the longer-winded description
that
myCircle
is a variable that contains a reference to a
Circle
object.
object vs. object reference
variable
Note
Arrays are treated as objects in Java. Arrays are created using the
new
operator. An array
variable is actually a variable that contains a reference to an array.
array object
9.5.2 Accessing an Object's Data and Methods
In OOP terminology, an object's member refers to its data fields and methods. After an object
is created, its data can be accessed and its methods can be invoked using the
dot operator
(
.
),
also known as the
object member access operator
:
dot operator (
.
)
■
objectRefVar.dataField
references a data field in the object.
■
objectRefVar.method(arguments)
invokes a method on the object.
Search WWH ::
Custom Search