Loading... ### 概要: 首先我们提供A类和B类,让B类继承A类,通过B类与A类中方法的输出了解真相!(A为父类,B为子类) ### A类: ```java class A{ { System.out.println("父类代码块"); this.showInfo(); } void find(){ System.out.println("父类中的find方法!"); } void showInfo(){ System.out.println("父类中的showInfo方法!"); System.out.println(this); this.find(); } } ``` ### B类继承A类: ```java class B extends A{ { System.out.println("子类代码块"); } void find(){ System.out.println("子类中的find方法!"); } void showInfo(){ System.out.println("子类中的showInfo方法!"); System.out.println(this); super.showInfo(); } } ``` ### 输出结果: ```java public class Test { public static void main(String[] args) { final B b = new B(); } } ``` 当我们执行上面代码输出结果为:  ### 解释:  <div class="tip inlineBlock success"> * 我们首先创建了一个B对象(B = new B();) * 代码块随着对象的创建而执行,首先执行了父类(A)中的代码块(第一条输出:父类代码块) * 父类(A)中代码块调用了当前对象(this)的showInfo()方法,输出当前对象,即为我们第一步实例化的子类(B)对象。(第二条输出:子类中的showInfo()方法!,第三条输出:test.B@61bbe9ba) * 调用了父类(super)的showInfo()方法,输出当前对象,即为我们第一步实例化的子类(B)对象。(第四条输出:父类中的showInfo()方法,第五条输出:test.B@61bbe9ba) * 通过父类(A)的showInfo()方法调用当前对象(this)的find()方法,即为子类(B)的find()方法。(第六条输出:子类中的find方法!) * 最后执行子类的代码块(第七条输出:子类代码块) </div> ### 总结: <div class="tip inlineBlock info"> 不管this在父类中出现还是在子类中出现,this都指向的是当前对象,而当前对象就是我们子类的实例化对象,所以在父类中通过this调用的方法都为我们子类的方法(前提条件:在父类调用前,子类重写了父类的方法,不然通过this调用的方法还是父类的方法) </div> 最后修改:2022 年 07 月 16 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 1 如果文章有用,请随意打赏。