Review:
Reference data types and objects
Reference data types and objects
Illustrated
Reference variables
and objects are
stored as follows:
Circle is a reference data type
circle1 is a reference variable
circle1 references (points to) a Circle object
|
We
create variables
to
store the
properties of
a
new
object when we
create the
object
The
behavior of
an object (=
program
instructions)
is stored
when Java
compiles the
class definition
Accesing
members of an object
- An object's
member
can refer to:
- A
data field in
the object
or
- A
method in
the object
|
- After an object is created,
its data can be
accessed
and its
methods
can be invoked
using the
dot operator (.):
objectRefVar.dataField references a data field in the object.
objectRefVar.method(arguments) invokes a method on the object
|
- The dot (.) operator is
also known as the
object member access
operator
Example:
circle1.radius
|
Accessing
members of an object
Example
public static void main()
{
Circle circle1 = new Circle(); // Create a Circle object circle1
Circle circle2 = new Circle(2); // Create a Circle object circle2
circle1.radius = 10; // Access the radius in circle1 object
circle2.radius = 99; // Access the radius in circle2 object
double area1 = circle1.getArea(); // Invoke getArea() method on circle1
double area2 = circle2.getArea(); // Invoke getArea() method on circle2
}
|
DEMO:
demo/03-classes/06-access-members
Terminology:
instance method
- The method
getArea( )
is invoked
as an operation
on a
specific
Circle object.
- The method
getArea( )
is referred to
as an
instance method,
because you invoke it only
on a
specific instance.
|
Reference typed variables and
primitive typed variables
are stored
differently
- All variables consist
of memory cells that can
store a
value (binary number)
- A variable of
a
primitive type
stores the
value itself
- A variable of
a
reference type
stores a
reference (= memory address)
of the location of
the
object
(= properties of the
object)
- The program must
use the
reference to
access the
object (properties)
|
Schematically:
|
An
important consequence
of the difference way of storing variables
-
Assigning to
variables of
primitive type will
make a
(real) copy:
- Update using
c will
not change
k:
public static void main(String[] args)
{
int k = 5;
int c = k;
c = 99; // Does not update k
System.out.println(k); // Prints 5
}
|
|
An
important consequence
of the difference way of storing variables
DEMO:
demo/03-classes/07
Why Java have
reference typed variables and
primitive typed variables
-
Variables
of a primitive data type can
only store
1 value but can
be accessed
quickly
- Such variables are
mainly used in
computations
|
-
Objects can have
many data fields
and can allow the
programmer to
represent
complex things in the
real world
- Objects are
mainly used for
data representation
- Accessing to
data in an
object is
slower
(need 2 memory accesses)
|
|
❮
❯