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

user8865657 :

I have been studying Inheritance in Java and the writer makes the statement "it is the type of object being referred to (not the type of reference variable) that determines which version of an overridden method will be executed." This statement is awfully confusing.

Robert Columbia :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464295&siteId=1