Reputation: 39
I learned that when constructing an object, super()
will be called, whether you write it in the constructor or not. But I noticed that in some code, the super()
method is called explicitly. Should I be calling super()
implicitly or explicitly in a constructor? What's the difference?
Upvotes: 2
Views: 1950
Reputation: 327
There is no difference if the discussion is around no-argument super()
constructor.
Java calls super()
implicitly for all your base class constructors if not called explicitly. Remember Java only calls super class no-argument constructor always.
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, ...)
IMO, avoid calling no-argument super()
constructor since it neither have any impact on logic nor improves readability.
Upvotes: 4
Reputation: 718798
Should I call the super() method implicitly or explicitly in a constructor? What's the difference?
There is no semantic difference between calling super()
or not, and no performance difference either.
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. And if the superclass doesn't have a no-args constructor, then you can't use super()
, either explicitly or implicitly.
Upvotes: 4