父类中的this

      父类中的this到底指向的是父类还是子类?为此做了下实验,代码如下:
   
   
public class ThisInParent {
 
public ThisInParent() {
}
public static void main(String[] args) {
new Child();
new P();
}
}
class P {
public P() {
System.out.println(this.getClass().getName());
this.f();
}
 
public void f() {
System.out.println("parent");
}
}
 
class Child extends P {
public Child() {
 
}
 
public void f() {
System.out.println("child");
}
 
}
运行该类得到的结果如下:
   
   
       
       
Child
child
P
parent

从上述结果看出:
(1)new Child的过程中,作为Child的直接父类P因为子类的隐式调用也进行了构造器的调用,输出结果为类名Child和方法f()输出child,可以看出此时的this代表的是子类的引用,并且调用f()时调用的是子类重写的父类方法,更加证明了this为子类的引用。
(2)另外直接new P父类的过程中,直接输出了P,parent的结果。
所以由以上结论得出,具体new那一个对象,如果在其父类中有对this 的引用,则该this一律指向的的是该被new的子类。
下面有一个三层继承的例子,可以更好的加以佐证
   
   
public class ThisInParent {
 
public ThisInParent() {
}
 
public static void main(String[] args) {
new GrandChild();
new Child();
new P();
}
}
 
class P {
public P() {
System.out.println(this.getClass().getName());
this.f();
}
 
public void f() {
System.out.println("parent");
}
}
 
class Child extends P {
public Child() {
System.out.println(this.getClass().getName());
this.f();
}
 
public void f() {
System.out.println("child");
}
 
}
class GrandChild extends Child {
public GrandChild() {
}
public void f(){
System.out.println("grandChild");
}
}
输出结果:
   
   
GrandChild
grandChild
GrandChild
grandChild
Child
child
Child
child
P
parent


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值