Calling super()
If you provide a class like this:
public class Foo
{
}
or this:
public class Foo()
{
public Foo()
{
}
}
the compiler will generate code for this:
public class Foo()
{
public Foo()
{
super();
}
}
So, strictly speaking, the call to "super()" is always there.
In practice you should only call "super(...)" where there are parameters you want to pass to the parent constructor.
It isn't wrong to call "super()" (with no parameters) but people will laugh at you :-)
You would need to use super()
in a case like this:
public class Base {
public Base(int foo) {
}
}
public class Subclass extends Base {
public Subclass() {
super(15);
}
}
This is a very contrived example, but the only time that you need to call super()
is if you're inheriting from a class that doesn't provided a default, parameterless constructor. In this cases you need to explicitly call super()
from the constructor of your subclass, passing in whatever parameters you need to satisfy the base class's constructor. Also, the call to super()
must be the first line of your inherited class's constructor.
There is no need to call super().
From Accessing Superclass Members :
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
As has been said, if your constructor does not explicitly call super() with or without some argument, java will automatically call the default constructor of the superclass.
However, explicitly calling super() is just that--explicit. If you know the superclass's constructor does something significant, it's a useful reminder to whomever is maintaining your code that super() is being called first (and may have side effects). This might even be a useful spot to put a breakpoint while debugging.