Java 中的引用变量究竟是什么?它与其他变量有何不同? [英] What exactly is a reference variable in Java? How does it differ from other variables?

查看:54
本文介绍了Java 中的引用变量究竟是什么?它与其他变量有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究 Java 中的继承,作者声明是被引用的对象类型(而不是引用变量的类型)决定了将执行哪个版本的重写方法."这个说法非常混乱.

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.

推荐答案

本书所指的是多态,更具体地说是通过动态调度.

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?");
    } 

}

现在,让我们创建一个 Person 类型的引用变量.

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

Person myBFF;

让我们实例化他

myBFF = new NewYorker();

请他自我介绍

myBFF.introduceYourself();

打印:

哟.你有问题吗?

现在,让我们将您的 BFF 更改为德克萨斯人.

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

myBFF = new Texan();

让我们再次拨打同一条线路,让我们的 BFF 自我介绍.

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

myBFF.introduceYourself();

打印:

大家好!

在每种情况下,您使用的引用变量都是 Person 类型.在每种情况下,变量的实例分别是 NewYorkerTexan.那个实例类型决定了introduceYourself()的哪个版本被调用.

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.

这篇关于Java 中的引用变量究竟是什么?它与其他变量有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆