简单小Demo,根据执行顺序来理解this关键字
public class Father {
public void init(){
System.out.println("1 father init");
this.run();
}
public void run() {
System.out.println("2 father run");
}
}
public class Son extends Father {
@Override
public void init() {
super.init();
System.out.println("3 son init");
}
@Override
public void run() {
System.out.println("4 son run");
}
public static void main(String[] args) {
Son son = new Son();
son.init();
}
}
执行顺序为
1 father init
4 son run
3 son init
出现这样的结果,而不是 1 2 3,是因为当前的运行类为son,所以当其调用super.init()时,相当于把son对象传递到父类,那么父类init方法中的this代表的是son ,所以调用的也就是son的run方法;