【发布时间】:2019-07-18 10:29:38
【问题描述】:
我正在通过继承使用子关系和父关系。我编写了一个代码,其中我在 Parent 类的方法中使用了 'THIS' 关键字,并且在我的 Child 类中覆盖了相同的方法。当我使用“Super”关键字从子类覆盖方法调用父类方法时,然后在父类方法中,“THIS”关键字表示子对象类,当我使用“THIS”关键字从父类方法调用方法时,它调用子类方法(此方法相同,也可在父子类中使用覆盖)。
class Parent {
void onResume() {
println("Parent:OnResume" + this) // Here 'this' denotes Child class's Object
this.show() // here Child class's method is invoked
show() // here Child class's method is invoked as well
}
void show() {
println("Parent:Show")
}
}
class Child extends Parent {
override
void onResume() {
super.onResume()
println("Child:->OnResume" + this)
}
override
void show() {
println("Child:Show")
}
}
//Calling code
Parent parentRef = new Child()
parentRef.onResume()
如果我使用父类引用变量创建子类对象
Parent parentRef = new Child()
然后'this'表示Parent类的onResume()方法中的Child对象,当我们在Parent中调用show()方法时,它会调用Child类的show()方法。
请让我清楚为什么会这样。据我所知,“this”指的是类的当前对象,所以这里为什么“this”指的是来自父类的子对象。 为此,请提供深入的内部细节。提前致谢。
【问题讨论】:
-
没有
THIS关键字。但是有thiskeyword,它表示调用实例方法时的current 对象。在这种情况下,它显然是Child的一个实例。不清楚你在问什么。 -
这里有两个对象,一个是我创建的子对象,另一个是内部创建的父类对象。那么这里为什么不使用'this'关键字在父类中引用父类对象?
-
请提供详细的内部细节。 这不是因为任何内部原因。这是因为语言规范是这样说的。
标签: java inheritance this