什么时候需要显式调用超类构造函数?

假设我有一个子类,它扩展了一个超类。在什么情况下需要显式键入 super()来运行超类构造函数?

我正在看一本关于抽象类的书中的一个例子,当他们用一个非抽象的子类来扩展它时,子类的缺省构造函数是空的,并且有一条注释说超类的缺省构造函数将被调用。与此同时,我也在这里看到了一些实例,其中有些人的问题没有明确调用 super()

调用超类的 default/non-default 构造函数与调用子类的 default/non-default 构造函数是否有区别?

60545 次浏览

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.

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...

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.