0

Like the example below. I know that the super keyword can be deleted in this case. But I don't get why Eclipse always generates this keyword by default. This keyword should mean nothing unless the SuperExample class extends another class?

public class SuperExample {

    private int x;

    public SuperExample(int x) {
        super();
        this.x = x;
    }
}
kencheng
  • 3
  • 2
  • Super(int x) is not a constructor for your class. Refer this for more - https://stackoverflow.com/questions/26264302/is-calling-supers-constructor-redundant-in-this-case – Sree Oct 19 '20 at 04:24

1 Answers1

3

Every class extends java.lang.Object by default, even if not specified. If there is construction to be done in Object that isn't done in SuperExample, then the call to super() in SuperExample.SuperExample() will make sure that processing happens.

Now, you're right in that the super() call isn't really necessary in this case, because Object doesn't actually do anything in particular in its own constructor. But your IDE will insert the call to super() anyway, because, well, why not? Including a call to super() is good practice even if the superclass doesn't do anything important in its constructor, because maybe sometime in the future it will.

It'd be more effort for Eclipse to check that your class extends something other than Object before auto-generating the super() call in the constructor. And doing so doesn't hurt anything, so why waste the effort optimizing it? That's the main reason.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53