Calling an overridden method from a constructor

后端 未结 4 940
滥情空心
滥情空心 2021-02-15 09:22

In the following example:

class Base {    
    int  x=10;  

    Base() {    
      show();
    }  

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


        
4条回答
  •  既然无缘
    2021-02-15 10:02

    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.

提交回复
热议问题