Inheritance and the “this” keyword

前端 未结 5 1709
有刺的猬
有刺的猬 2020-12-31 09:29

Suppose that we have next situation:

Parent class A:

class A{  
    public A(){}
    public doSomething(){  
        System.out.println(this.getCla         


        
5条回答
  •  死守一世寂寞
    2020-12-31 10:14

    The output of program is correct.

    When in Main class ab.doSomething(); line get executed doSomething() method of class B will be called then super.doSomething(); line will call doSomething() method of class A. As this keyword indicates reference of current object(ab is the object of class B see A ab=new B(); as constructor is of class B),i.e.System.out.println(this.getClass()); line in class A will print B only.

    Again control will come back to System.out.println(this.getClass());in class B, So again B will get print.

    In birdeye view only object of class B has created. That is why we are getting B B in output.

提交回复
热议问题