2

this code from ArrayList source:

public ArrayList() {
    super();
    this.elementData = EMPTY_ELEMENTDATA;
}

this code from AbstractList source:

protected AbstractList() {
}

What does super() do?

zeds
  • 137
  • 1
  • 10

2 Answers2

4

In general, super will invoke its parent constructor with matching arguments. In this case, because AbstractList has an implicit no-arg constructor, we use super() with no arguments to invoke the implicit no-arg constructor.

As to why - there's really no reason to do it in this case, if there's no requirement to set fields in the parent class. This may have been a case of an older style of programming.

It does no harm, and it's self-documenting; it's explicit in that it calls its parent's constructor. Although, I will note that the Javadoc for that constructor calls out its invocation usefulness:

/**
 * Sole constructor.  (For invocation by subclass constructors, typically
 * implicit.)
 */

You're more likely to see implicit invocations of that constructor than you are explicit.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 1
    Could also be here to anticipate a version where the constructor of `AbstractList` will actually do something – ortis Nov 28 '14 at 17:20
  • Considering that `AbstractList` has been around since 1.2, I genuinely doubt that they were anticipating something with that constructor. It could also be a legacy holdover. I'm not sure; I'd have to pull down the source code history to tell you for certain. – Makoto Nov 28 '14 at 17:21
-1

super() call parent constructor.

super() is never needed, however it is not a bad habit to write it, because it is good for readability - it reminds you that parent constructor is called.

See this question When do you need to explicitly call a superclass constructor?

Community
  • 1
  • 1
Michal Krasny
  • 5,434
  • 7
  • 36
  • 64