小编slo*_*mir的帖子

继承和"this"关键字

假设我们有下一个情况:

家长A:

class A{  
    public A(){}
    public doSomething(){  
        System.out.println(this.getClass());
    }
}
Run Code Online (Sandbox Code Playgroud)

带着孩子B级:

class B extends A{  
    public B(){}
    public void doSomething(){
        super.doSomething();
        System.out.println(this.getClass());
    }
}
Run Code Online (Sandbox Code Playgroud)

和主要课程:

class Main{  
    public static void main(String[] args){
        A ab=new B();
        ab.doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我执行此代码时,结果是

B  
B
Run Code Online (Sandbox Code Playgroud)

为什么this在超类A中引用,B引用是类型A 时返回为类?

java inheritance this

12
推荐指数
3
解决办法
6725
查看次数

标签 统计

inheritance ×1

java ×1

this ×1