First, you don't have to create a parent instance (Parent
) to instantiate a child class (Employee
). You must have understood wrong.
Invoking the constructor of the parent class doesn't mean to create a new parent instance object (you're not calling it with new
, so no new instance is created). You are creating a child instance, and for this, you need to first invoke the parent's constructor because of inheritance. Imagine for example the parent class has private
fields that must be initialized in the constructor (for example private final
fields). This fields cannot be accessed from the child class, but they can be initialized from the parent class constructor. You need to initialize this fields in the child instance, and the only way is calling super()
.
In this case Person
has a default contructor which is invoked by default, no need to explicitly call it.
But in case Person
has no default constructor, you need to call it explicitly. For example:
public class Person{
private final String name;
public Person(final String name) {
this.name = name;
}
}
public class Employee extends Person {
public Employee() {
}
}
This will not compile. You need to modify Employee
so it calls Person
constructor explicitly. For example:
public class Employee extends Person {
public Employee(final String name) {
super(name);
}
}