在这段代码中
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
,但是 a
是 child
和 this
为当前对象引用,即a
。 b
的值为 a
。
然后你执行
b.show();
调用child#show
,所以程序会输出“child”。
关于java - return this 在这段代码中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24807222/