Reference Types in Java - dummies

By Doug Lowe

A reference type is a data type that’s based on a class rather than on one of the primitive types that are built in to the Java language. The class can be a class that’s provided as part of the Java API class library or a class that you write yourself.

Either way, when you create an object from a class, Java allocates the amount of memory the object requires to store the object. Then, if you assign the object to a variable, the variable is actually assigned a reference to the object, not the object itself. This reference is the address of the memory location where the object is stored.

To declare a variable using a reference type, you simply list the class name as the data type. For example, the following statement defines a variable that can reference objects created from a class named Ball:

Ball b;

You must provide an import statement to tell Java where to find the class.

To create a new instance of an object from a class, you use the new keyword along with the class name:

Ball b = new Ball();

One of the key concepts in working with reference types is the fact that a variable of a particular type doesn’t actually contain an object of that type. Instead, it contains a reference to an object of the correct type. An important side effect is that two variables can refer to the same object.

Consider these statements:

Ball b1 = new Ball();
Ball b2 = b1;

Here, both b1 and b2 refer to the same instance of the Ball class.