简体   繁体   English

应该隐式或显式调用super()吗?

[英]Should super() be called implicitly or explicitly?

I learned that when constructing an object, super() will be called, whether you write it in the constructor or not. 我了解到,构造对象时,无论是否在构造函数中编写,都将调用super() But I noticed that in some code, the super() method is called explicitly. 但是我注意到在某些代码中, super()方法被显式调用。 Should I be calling super() implicitly or explicitly in a constructor? 我应该在构造函数中隐式或显式调用super()吗? What's the difference? 有什么不同?

Should I call the super() method implicitly or explicitly in a constructor? 我应该在构造函数中隐式或显式调用super()方法吗? What's the difference? 有什么不同?

There is no semantic difference between calling super() or not, and no performance difference either. 是否调用super()之间没有语义差异,也没有性能差异。

This is purely a cosmetic issue. 这纯粹是一个表面问题。 Make up your own mind ... or go with what (if anything) your project's adopted style guide says. 下定主意...或遵循项目采用的样式指南的内容(如果有的话)。


On the other hand, if the super you need to call has parameters, then it does matter that you call it explicitly. 在另一方面,如果super您需要调用具有参数,那么非常重要,你明确地调用它。 And if the superclass doesn't have a no-args constructor, then you can't use super() , either explicitly or implicitly. 而且,如果超类没有no-args构造函数,则不能显式或隐式使用super()

There is no difference if the discussion is around no-argument super() constructor. 如果讨论是围绕无参数 super()构造函数进行的,则没有任何区别。

Java calls super() implicitly for all your base class constructors if not called explicitly. 如果未显式调用Java,则对所有基类构造函数隐式调用super() Remember Java only calls super class no-argument constructor always. 请记住,Java始终仅调用超类无参数构造函数。

In some cases, as a developer you may want to call argument-based super constructor. 在某些情况下,作为开发人员,您可能需要调用基于参数的超级构造函数。 In those cases, you have to explicitly call argument-based super constructor eg: super(arg1, arg2, ...) 在这些情况下,您必须显式调用基于参数的超级构造函数,例如: super(arg1, arg2, ...)

IMO, avoid calling no-argument super() constructor since it neither have any impact on logic nor improves readability. IMO,避免调用无参数的super()构造函数,因为它既不会对逻辑产生任何影响,也不会提高可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM