Database Reference
In-Depth Information
handing and setting memory pointers or references). The
main()
method is unique, and I will discuss it
more when I cover the
static
modifier, a little later.
public static void main( String[] args ) {
MyApp2 m = new MyApp2();
MyRef useRef = new MyRef();
m.setRef( useRef );
ARRAY mA = m.getArray();
myRef = new MyRef();
}
Objects
The words
object
,
class
, and
instance
are practically interchangeable. You have classes (theoretically)
before you create any instances. An instance only exists when you instantiate a new one in memory. You
have objects that you can move around and store even if you don't know what type they are. Objects can
be placed on disk or sent across the network, even when they don't exist as instances in memory.
So, you create an instance in memory of a class type, which is an object that can be moved out of
memory (stored on disk), at which point it is not an instance, but can still exist as an object.
Classes and Null
I have already used the term
instance
in our discussion. In Listing 3-3, there are three instances of classes
being created. To pick out the instances, look for the word
new
. Whenever you see the statement
new
, an
object is being instantiated.
Sometimes you will call other classes in order to get an instance of some type; however, even though
you don't use the word
new
in your code, that word was used somewhere down the line to get the
instance. In the example code for
MyApp2
, we see the
main()
method setting the member
mA
equal to an
ARRAY
that is returned from the method
getArray()
. You may notice that the
getArray()
method in
MyApp2
does not use the
new
statement, and when we define
myArray
at the class level (top), we do not say
new
. Instead, we used the word
null
in the definition. When the method
getArray()
returns
myArray
, it is
returning a
null
instead of an instance of
ARRAY
. And when the
main()
method set
mA
equal to what's
returned from
getArray()
, it is setting
mA
equal to
null
. This is not very productive, but it is valid Java
code.
To explain
null
, we will consider what the following statements mean:
MyRef useRef = new MyRef();
new MyRef();
ARRAY myArray;
ARRAY myArray = null;
The first line instantiates a new instance of
MyRef
class and assigns a member reference (name) to it.
The name we will use is
useRef
.
We can instantiate a new instance without assigning it to a name as in the second line. This is often
done in graphical user interface (GUI) apps when they get started. The initial
Frame
is instantiated and
displays itself on screen—no name is required.
We can also create a new name for a certain type of class and not assign it to any instance, as in the
third line. The fourth line is identical in effect to the third line except that in the fourth line we are
specifically telling Java that we are assigning the member name
myArray
to a non-existent instance,
hence
null
. In effect,
myArray
points at
no
memory location.