核心点:
super关键字,表示调用的是父类对象。
this关键字,表示调用的是当前运行类对象。
那么如果在父类中,使用了关键字,this,此时的this指的是什么呢?
看下面的例子,再加深理解核心店的第二句话就ok了。
parent类:
package com.ghsy.thissuper;
public class Parent {
public void init(){
System.out.println(this.getClass()); //获得当前运行类
System.out.println(this.getClass().getSuperclass()); //获得当前运行类的父类
System.out.println("1 parent init");
this.demo();
}
public void demo(){
System.out.println("2 parent demo");
}
public static void main(String[] args) {
Parent parent = new Parent();
parent.init();
}
}
son类:
package com.ghsy.thissuper;
public class Son extends Parent{
public void init(){ //JVM获得隐式传递 this获得
super.init(); // Parent.init(son);
System.out.println("3 son init");
this.demo();
}
public void demo(){
System.out.println("4 son demo");
}
public static void main(String[] args) {
Son son = new Son();
son.init(); //Son.init(son)
}
}
分别在以上两个类的六个方法中打上六个断点,然后用eclipse进行debug,同时追踪this关键字值的变化。会有如下发现。
当调用super.init()时候,程序走到parent方法的init方法位置。显然这里的super关键的作用,调用父类对象的方法的时候使用。
接着往下走断点,发现打印的this.getclass的结果是son,同时在debug模式下,元素跟踪框中this关键字,也是son实例。
从此可以看出,即使在子类中调用了父类的方法,在父类中执行方法时,使用this关键字,此时的this不是指此时的父类。
而仍然当前的运行类son类的实例。既然this,仍然代表son。那么断点继续往下走,调用父类中的init方法中的this.demo方法
会出现什么结果呢?其实还是son.demo(),如果子类son类,没有此方法,则会调用父类的此方法。
所以最终还是一句话,this关键字,指的是当前运行类的实例。所有再设计父子类继承关系的时候,要有所注意的。
上述程序,从son类运行的结果1434;从parent类运行结果1,2.