关于子类创建对象调用父类方法时this的问题(以及方法重写)

xiaoxiao2021-03-01  16

如下实例提出问题:

class T{    T(){        System.out.println("T()");    }   void foo(){this.bar();}   void bar(){       System.out.println("T.bar");   }}class B extends T{    B(){        System.out.println("B()");    }   void foo(){       super.foo();   }   void bar(){       System.out.println("B.bar");   }}public  class test {    public static void main(String[] args) {        B b=new B();        b.foo();    }}

结果输出如下:

其实我相信这样的结果可能大家都是惊讶的,b.foo()实际是调用了父类中的foo()方法,方法主体为this.bar

由结果可以得到this实际指的是子对象。

分析:

由输出结果可见,当创建子类对象时首先调用了父类的构造方法,再调用子类的构造方法,值得注意的是传给父类构造方法的this指针和传给子类构造方法的this指针完全相同,也就是说调用父类构造方法的并不是父类的对象,所以在创建子类对象时并没有创建父类对象。this指向的仍然是子对象,同时由于子类重写了父类的bar()方法,所以输出为B.barr

在原代码上做轻微改动如下:

class T{    T(){        System.out.println("T()");    }   void foo(){this.bar();}   void bar(){       System.out.println("T.bar");   }}class B extends T{    B(){        System.out.println("B()");    }   void foo(){       super.foo();   } /*void bar(){       System.out.println("B.bar");   }*/}public  class test {    public static void main(String[] args) {        B b=new B();        b.foo();    }

}

输出结果如下:

由于此时子类并未重写父类方法,故输出为T.bar

转载请注明原文地址: https://www.6miu.com/read-3100029.html

最新回复(0)