Sub topic 6
Chain Constructors with super(...)
A constructor is a special block of code that runs when you create a new object. It sets up the object's starting values. When one class extends another, each class has its own constructor. The subclass constructor must make sure the superclass constructor runs too. This process is called constructor chaining.
What a Constructor Does
A constructor has the same name as its class and no return type. Here is a simple one:
class Animal {
private String name;
Animal(String name) {
this.name = name;
}
}When you write new Animal("Rex"), Java runs this constructor. The value "Rex" is stored in the name field.
Why the Parent Constructor Runs First
A subclass object contains the parts of its superclass. Those parts need to be set up before the subclass adds its own details. So Java always runs the superclass constructor first.
You control this with super(...). The keyword super refers to the superclass. Writing super(name) calls the superclass constructor and passes it name.
A Worked Example
This program creates a Dog. The Dog constructor hands the name to the Animal constructor.
class Animal {
private String name;
Animal(String name) {
this.name = name;
System.out.println("Animal constructor ran");
}
String getName() {
return name;
}
}
class Dog extends Animal {
private String breed;
Dog(String name, String breed) {
super(name);
this.breed = breed;
System.out.println("Dog constructor ran");
}
String getBreed() {
return breed;
}
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex", "Beagle");
System.out.println(rex.getName() + " is a " + rex.getBreed());
}
}The output is:
Animal constructor ran
Dog constructor ran
Rex is a BeagleThe Animal part runs first. Then the Dog part finishes its work.
The Rules
| Situation | What happens |
|---|---|
| You write `super(name)` | Java calls the matching superclass constructor |
| You write no `super` call | Java inserts `super()`, which needs a no-argument superclass constructor |
| The superclass has only `Animal(String name)` and you write no `super` call | The code does not compile |
Try It
Exercise
The Animal class has only the constructor Animal(String name). The Dog constructor has no super(...) call. Does the code compile?
Show answer
No. Java inserts super() automatically. Animal has no no-argument constructor, so the compiler reports an error. To fix it, add super(name) as the first line of the Dog constructor.