Is it unnecessary to put super() in constructor?

Firstly some terminology:

  • No-args constructor: a constructor with no parameters;
  • Accessible no-args constructor: a no-args constructor in the superclass visible to the subclass. That means it is either public or protected or, if both classes are in the same package, package access; and
  • Default constructor: the public no-args constructor added by the compiler when there is no explicit constructor in the class.

So all classes have at least one constructor.

Subclasses constructors may specify as the first thing they do which constructor in the superclass to invoke before executing the code in the subclass’s constructor.

If the subclass constructor does not specify which superclass constructor to invoke then the compiler will automatically call the accessible no-args constructor in the superclass.

If the superclass has no no-arg constructor or it isn’t accessible then not specifying the superclass constructor to be called (in the subclass constructor) is a compiler error so it must be specified.

For example:

public class Base { }
public class Derived extends Base { }

This is fine because if you add no constructor explicitly Java puts in a public default constructor for you.

public class Base { }
public class Derived extends Base { public Derived(int i) { } }

Also fine.

public class Base { public Base(String s) { } }
public class Derived extends Base { }

The above is a compilation error as Base has no default constructor.

public class Base { private Base() { } }
public class Derived extends Base { }

This is also an error because Base’s no-args constructor is private.

Leave a Comment