Calling an overridden method from a constructor

后端 未结 4 1170
醉话见心
醉话见心 2021-02-15 09:55

In the following example:

class Base {    
    int  x=10;  

    Base() {    
      show();
    }  

    void show() {   
        System.out.print (\"Base Show \         


        
4条回答
  •  伪装坚强ぢ
    2021-02-15 09:58

    You can call overriden methods from constructors, but it's bad and you shouldn't. You illustrated the reason why this is bad: the derived class doesn't get a chance to get initialized, so uninitialized fields will be used - in your example, the default for int x is 0, that's why it's printing 0.

提交回复
热议问题