继承与"this"关键词 [英] Inheritance and the "this" keyword
本文介绍了继承与"this"关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有下一种情况:
Suppose that we have next situation:
父类A:
class A{
public A(){}
public doSomething(){
System.out.println(this.getClass());
}
}
有B级子班的孩子:
class B extends A{
public B(){}
public void doSomething(){
super.doSomething();
System.out.println(this.getClass());
}
}
和主班:
class Main{
public static void main(String[] args){
A ab=new B();
ab.doSomething();
}
}
当我执行此代码时,结果是
When I execute this code result is
B
B
为什么当 reference 的类型为A时,在超类A中引用的this
返回B
作为类?
Why does this
, referenced in superclass A, returns B
as a class when the reference is of type A?
推荐答案
引用无关紧要,它是实例化对象的类.您正在创建的对象的类型为B,因此this.getClass()总是会返回B.
It doesn't matter what the reference is, it's the instantiated object's class that counts. The object that you're creating is of type B, therefore this.getClass() is always going to return B.
这篇关于继承与"this"关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文