Lesson: Reference Variables

Overview: 
Explore Reference (object) variables.
Objectives: 

Understand the basic concept of reference variables and how we use objects through reference variables.

Content: 

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 (definition) is the reference variable's data type. This is how you create your own data types in Java, by creating classes. A reference variable is initialized by setting it to a new instance of an object or setting it equal to an existing object instance:

A class describes the data type of an object, that is, the variables and methods that comprise the object. An object is just a bundle of data and actions. You create an actual instance of the object in by using the new operator. New allocates the memory needed to hold the object instance 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.

 

Navigation: