java - return this 在这段代码中做了什么?

标签 java

在这段代码中

class Parent {

    void show() {
        System.out.print("parent");
    }

    Parent a() {
        return this;
    }

}

class Child extends Parent {

    void show() {
        System.out.print("child");
    }

    public static void main(String arg[]) {
        Parent a = new Child();
        Parent b = a.a();
        b.show();
    }
}

return this; 做什么? b.show() 正在调用子方法 show。那么 this 是否返回对其子类的引用?如果不是,那么如何调用 child 的 show() 方法?

最佳答案

首先,Java中所有非私有(private)和非静态方法都是虚拟的,这意味着你将始终执行对象引用类型的方法。

在这种情况下,你有

parent a=new child();

这意味着使用 a 的客户端(类/方法)只能执行 parent 类中定义的方法,但行为由 child< 类型定义.

在此之后,当你执行:

parent b=a.a();

a.a() 将返回 this,但是 achildthis为当前对象引用,即ab 的值为 a

然后你执行

b.show();

调用child#show,所以程序会输出“child”。

关于java - return this 在这段代码中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24807222/

相关文章:

java - JPA : Error in your SQL syntax in spring entity

java - 以编程方式创建可独立控制的相同 ImageView

java - 获取实体的存储库

java - 如何限制 JPA Batch 查询的内存使用?

java - 无法读取上传到 Azure Blob 的文件

java - 非 volatile 变量是否需要同步?

java - 使用Spring的WebApp找不到bean

java - 使用 split.String ("") 将字符串拆分为子字符串;

java - 具有 oAuth : get the current ClientId 的端点

java - 在一个浏览器中使用带有多个选项卡的 JSF