Instructional Material: Reference Variables

Printer-friendly version

We are going to briefly introduce objects and classes so we can discuss reference variables. An object is just a bundle of data (variables) and actions (methods). A class describes the the variables and methods that comprise an object and so acts as the "data type" of an object. This is how you create your own data types in Java, by creating classes.

Unlike primitive data types, which store actual values, reference variables store a reference (or pointer) to an instance of an object. Here the object's class is the reference variable's data type. A reference variable is initialized by setting it to a new instance of an object or setting it equal to an existing object instance:

 You create an actual instance of the object in by using the new operator. New 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 objects using the . (dot) accessor. For instance, all objects in Java have a default method called toString(). That method returns a string containing either a description or the contents of the object as appropriate. You would call toString() like this:

In this example, the contents of the string variable myString are returned by toString() and 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 would access it like this:

We are going to discuss methods, objects and classes in more detail later on. For now, watch this video about Strings.

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.


Material Type: 
Education Level: 
HW Platform: 
SW Platform: 
Interactivity Style: