Java Reference
In-Depth Information
Memory management in Java is dynamic and automatic. When you create a new object,
Java automatically allocates the correct amount of memory for that object. You don't
have to allocate any memory for objects explicitly. Java does it for you.
Because Java memory management is automatic, you do not need to deallocate the mem-
ory an object uses when you're finished using the object. Under most circumstances,
when you are finished with an object you have created, Java can determine that the
object no longer has any live references to it. (In other words, the object won't be
assigned to any variables still in use or stored in any arrays.)
As a program runs, Java periodically looks for unused objects and reclaims the memory
that those objects are using. This process is called garbage collection and occurs without
requiring any programming on your part. You don't have to explicitly free the memory
taken up by an object; you just have to make sure that you're not still holding onto an
object you want to get rid of.
3
Accessing and Setting Class and
Instance Variables
At this point, you could create your own object with class and instance variables defined
in it, but how do you work with those variables? Easy! Class and instance variables are
used in largely the same manner as the local variables you learned about yesterday. You
can use them in expressions, assign values to them in statements, and so on. You just
refer to them slightly differently from how you refer to regular variables in your code.
Getting Values
To get to the value of an instance variable, you use dot notation, a form of addressing in
which an instance or class variable name has two parts: a reference to an object or class
on the left side of the dot and a variable on the right side of the dot.
Dot notation is a way to refer to an object's instance variables and methods using a dot
( . ) operator.
For example, if you have an object named myCustomer , and that object has a variable
called orderTotal , you refer to that variable's value as myCustomer.orderTotal , as in
this statement:
float total = myCustomer.orderTotal;
This form of accessing variables is an expression (that is, it returns a value), and both
sides of the dot are also expressions. That means you can nest instance variable access. If
 
Search WWH ::




Custom Search