Say you have a Parent class and a Child class. To construct a Child instance always requires some Parent constructor to be run at the very gebinning of the Child constructor. We can select the Parent constructor we want by explicitly calling super(...)
with the appropriate arguments as our first Child constructor statement. Doing this saves us time by reusing the Parent classes' constructor instead of rewriting the same code in the Child classes' constructor.
Without super(...)
method:
(implicitly, the no-args version super()
is called invisibly)
class Parent {
private String name;
private int age;
public Parent() {} // necessary because we call super() without arguments
public Parent(String tName, int tAge) {
name = tName;
age = tAge;
}
}
// This does not even compile, because name and age are private,
// making them invisible even to the child class.
class Child extends Parent {
public Child() {
// compiler implicitly calls super() here
name = "John";
age = 42;
}
}
With super()
method:
class Parent {
private String name;
private int age;
public Parent(String tName, int tAge) {
name = tName;
age = tAge;
}
}
class Child extends Parent {
public Child() {
super("John", 42); // explicit super-call
}
}
Note: Calls to another constructor (chaining) or the super constructor MUST be the first statement inside the constructor.
If you call the super(...)
constructor explicitly, a matching parent constructor must exist (that's straightforward, isn't it?).
If you don't call any super(...)
constructor explicitly, your parent class must have a no-args constructor - and this can be either written explicitly or created as a default by the compiler if the parent class doesn't provide any constructor.
class Parent{
public Parent(String tName, int tAge) {}
}
class Child extends Parent{
public Child(){}
}
The class Parent has no default constructor, so, the compiler can't add super
in the Child constructor. This code will not compile. You must change the constructors to fit both sides, or write your own super
call, like that:
class Child extends Parent{
public Child(){
super("",0);
}
}