When do you need to explicitly call a superclass constructor?

大兔子大兔子 提交于 2019-11-26 07:24:52

问题


So say I have a subclass that extends a superclass. In what scenarios do I need to explicitly type super() to get the superclass constructor to run?

I\'m looking at an example in a book about abstract classes and when they extend it with a non-abstract subclass, the subclass\'s default constructor is blank and there\'s a comment that says the superclass\'s default constructor will be called. At the same time I\'ve also seen instances on here where someone\'s problem was not explicitly calling super().

Is the distinction from calling the superclass\'s default/non-default constructor from the subclass\'s default/non-default constructor?


回答1:


You never need just

super();

That's what will be there if you don't specify anything else. You only need to specify the constructor to call if:

  • You want to call a superclass constructor which has parameters
  • You want to chain to another constructor in the same class instead of the superclass constructor

You claim that:

At the same time I've also seen instances on here where someone's problem was not explicitly calling super().

Could you give any examples? I can't imagine how that's possible...




回答2:


If you don't explicitly call a super constructor the argument less constructor (super()) will be called. This means you have to call a specific constructor yourself if there's no reachable argument-less constructor of the super class.

But often enough you want a different constructor anyways even if you could use the default constructor - depends on your code.

Also note that if no constructor is declared the compiler generates a public default constructor automatically, but as soon as you write your own constructor this does not happen anymore.




回答3:


The super() method is always called in constructors of sub-classes, even if it is not explicitly written in code.

The only time you need to write it, is if there are several super(...) methods in the super-class with different initialization parameters.



来源:https://stackoverflow.com/questions/6318628/when-do-you-need-to-explicitly-call-a-superclass-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!