class C{
    public C() {
        System.out.println("C构造方法");
        this.print(); 
    }
    void print() {
        System.out.println("这是C中的this调用");
    }
}
 
class B extends C{
    public B() {
        System.out.println("B构造方法");
        this.print();
    }
    void print() {
        System.out.println("这是B中的this调用");
    }
}
class A extends B{
    public A() {
        System.out.println("A构造方法");
        this.print();
    }
    void print(){
        System.out.println("这是A中的this调用");
    }
}
 
 
public class Main {
    public static void main(String[] args) {
        A a = new A();
        System.out.println("=====================");
        B b = new A();
        System.out.println("=====================");
        C c = new A();
        System.out.println("=====================");
    }
}

就这么一看,先调用C构造方法,再调用B构造方法,最后调用A构造方法,可是C、B构造方法和A构造方法中都有this,难道是C里面的this是C对象,B里面的this是B对象,A里面的this是A对象?

看一下运行结果

C构造方法
这是A中的this调用
B构造方法
这是A中的this调用
A构造方法
这是A中的this调用
=====================
C构造方法
这是A中的this调用
B构造方法
这是A中的this调用
A构造方法
这是A中的this调用
=====================
C构造方法
这是A中的this调用
B构造方法
这是A中的this调用
A构造方法
这是A中的this调用
=====================

 

 

结果3个都是A对象,因为在main方法创建的都是A对象,A继承了B, B继承了C,实际运行的this就全是A对象,所以会执行A里面的方法。

 

=============================Talk is cheap, show me the code===========================