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 a class, which is an object. Here the object's class is the 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:

A class describes the data type of an object, that is, the variables and methods that comprise the object. You create an actual instance of the object 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(). You would call toString() like  this:

Methods are always specified with a parameter list () even it if 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 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: