Lesson: Reference Variables

Overview: 
Explore Reference (object instance) variables.
Objectives: 

Understand the basic concept of reference variables and how we access object instances through reference variables.

Content: 

Having introduced objects and classes we need to discuss reference variables. Classes, which describe objects, can be thought of as complex Data Types. When we create an object instance with the new operator, we put the return value of new into a variable whose Data Type is the class name. This kind of variable is a reference variable.

Unlike primitive data types, which store single data values, reference variables store a reference (or pointer) to the instance (the bundle of data) of an object we create with the new operator. A reference variable is initialized by setting it to a new instance of an object or setting it equal to an existing object instance:

The new operator allocates the memory needed to hold the object instance's variables and stores the location of that block of memory in the reference variable. You have one class that describes an object but could have many instances of the object allocated in your program.

Reference variables allow us to access the variables and methods contained in instances of objects using the . (dot) accessor. For example, all objects in Java have a built-in method called toString(). That method returns a string containing either a description of or the contents of the object, as appropriate. You would call toString() like this:

In this example, the contents of the String object instance pointed to by the variable myString is returned by toString() and that content is passed to the system method println() which prints the string of characters on the system console. This example shows how the output of one method can be passed directly to another method as long as the data type returned matches the data type expected.

Methods, when called, are always specified with a parameter list ( ), even if it is empty.

If an object had a integer variable called age, you could access it like this:

The Java String class mentioned above is a built in class that stores and manipulates strings of characters. Strings are used extensively in Java programs. Watch this video for more about Strings. Java also has built in classes for manipulating numbers, discussed in Unit 12.

Note that the compiler and JVM check reference variable data types just like with primitive data types. If a variable is typed as String, then only a String instance can be placed into the variable. Similarly, if you have a variable of type MyObject, only instances of MyObject can be placed into that variable.

 

Navigation: