2

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?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
AHoS
  • 39
  • 2
  • possible duplicate of [Why do we have to call super in Android sometimes?](http://stackoverflow.com/questions/10843383/why-do-we-have-to-call-super-in-android-sometimes) – princepiero Sep 12 '13 at 02:36
  • 1
    Doesn't matter unless you plan on passing parameters to the super class's constructor. The compiler inserts it for you if you leave it out. If there's no default c'tor in the superclass then you _must_ call it explicitly with the appropriate arguments passed to it. – sgbj Sep 12 '13 at 02:37
  • Thanks for answering. I was reading the source code of Exception class,when I found the default constructor of Excetion has only a super() inside. And I'm confused.Now I got it. – AHoS Sep 12 '13 at 02:43

2 Answers2

4

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
4

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.

kotacc
  • 327
  • 2
  • 12