#先上代码#
package com.xiaohe.c;
public class ParentBase
{
private String a;
private Integer b;
public static void main(String[] args) {
Sun sun = new Sun("1",2,"3");
System.out.println(sun.getParentA());
System.out.println(sun.getA());
}
public String getA() {
System.out.println(this);
return this.a;
}
public void setB(Integer b) {
this.b = b;
}
}
class Sun extends ParentBase {
private String c;
private String a;
public Sun(String a, Integer b, String c) {
this.a = a;
super.setB(b);
this.c = c;
}
public String getA() {
return this.a;
}
public String getParentA() {
return super.getA();
}
}
#监控截图#
上边两张图可以看出this的指向都是同一个内存空间,可能在此时你有一些疑问,父类中的this不就是子类对象自己吗?继续往下看,上图。
上图可以看出,如果this是指向子类的,那在父类中调用this.a 不应该是null,但是现在获取的是null,是不是有些疑问。继续看。
在子类中调用this.a 获取到的数据是有值的。此时你对继承是不是有些深入的思考了,我们再来做一个测试,在父类中调用只在子类中存在的成员变量。看看会有什么结果?上图
编译器报错!直接pass,以上就是对extends 中的this指向问题引发的思考,欢迎各位批评指正。