When do you need to explicitly call a superclass constructor?

后端 未结 3 1684
忘掉有多难
忘掉有多难 2020-11-27 12:46

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\

3条回答
  •  -上瘾入骨i
    2020-11-27 13:28

    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.

提交回复
热议问题