What exactly is a reference variable in Java? How does it differ from other variables?

What the book is referring to is polymorphism, more specifically through dynamic dispatch.

In a nutshell, imagine the following classes:

public class Person {

    public Person() {
    }

    public void introduceYourself() {
    } 

}

public class Texan extends Person {

    public Texan() {
    }

    public void introduceYourself() {
        System.out.printLn("Howdy y'all!");
    } 

}

public class NewYorker extends Person {

    public NewYorker() {
    }

    public void introduceYourself() {
        System.out.printLn("Yo. You got a problem with that?");
    } 

}

Now, let's create a reference variable of type Person.

Person myBFF;

Let's instantiate him

myBFF = new NewYorker();

Let's ask him to introduce himself

myBFF.introduceYourself();

This prints:

Yo. You got a problem with that?

Now, let's change your BFF to a Texan.

myBFF = new Texan();

Let's call that same line again and ask our BFF to introduce himself.

myBFF.introduceYourself();

This prints:

Howdy y'all!

In each case, the reference variable you were using was of type Person. The instance of the variable, in each case, was NewYorker and Texan respectively. That instance type determines which verson of introduceYourself() is called.


A reference variable is the type you specify on the left hand side (a variable that holds a reference type). What the author is referring to is when the right hand side then differs. Consider

Object a = new Foo(); 
System.out.println(a.toString());

if Foo overrides the Object.toString() (that is, if Foo provides a public String toString()) method then it is Foo's toString that is invoked (not Object's). See also Overriding and Hiding Methods in the Java tutorials.


A reference variable looks like this :

Coordinate cords; //Cords is the ref. var

Inside of that reference variable is an address inside of your computer's RAM which stores the attributes of that object. Since we did not instantiate (actually make an object of) the address of the aforementioned cords object is null

Reference variables hold addresses to reserved parts of memory.

cords = new Coordinate(0.0,0.0,0.0);

Now inside of the RAM of the computer is a reserved space that holds three floating type variables. Upon instantiation, a reference variable holds the address. So what can we do with addresses in Java?

Nothing of use. Java memory address are useless, and you can not see them(Though they look something like 0xFFFFFFF)

For a visual representation click here