Sub topic 6
Chain Constructors with super(...)
Why constructors need chaining
A constructor is a special block of code that sets up a new object. It has the same name as its class and no return type.
When you create a subclass object, you get two things in one object: the part defined by the superclass, and the part defined by the subclass. Both parts need setup. The superclass part is set up by the superclass constructor. The subclass part is set up by the subclass constructor.
Constructor chaining is the way Java links these constructors. Each constructor calls another one, until the chain reaches the top. The keyword super(...) is how a subclass constructor calls a constructor of its superclass.
This chapter assumes you know what a class, a field, and a constructor are. It also assumes you know the extends keyword.
Constructors are not inherited
A subclass does not inherit the constructors of its superclass. Inherited members are fields and methods. Constructors belong to the class that declares them.
Suppose Animal has a constructor that takes a name. Dog does not get that constructor for free. If you want new Dog("Rex") to work, Dog must declare its own constructor. That constructor then asks Animal to do its part.
Calling super(...)
Look at this complete program.
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
String getName() {
return name;
}
}
class Dog extends Animal {
private final String breed;
Dog(String name, String breed) {
super(name);
this.breed = breed;
}
String getBreed() {
return breed;
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Rex", "Beagle");
System.out.println(dog.getName() + " is a " + dog.getBreed());
}
}The output is:
Rex is a BeagleHere is what happens step by step.
new Dog("Rex", "Beagle")starts theDogconstructor.- The first line,
super(name), runs theAnimalconstructor with the value"Rex". - The
Animalconstructor stores the name. - Control returns to
Dog, which stores the breed.
The field name is private in Animal. Dog cannot write to it directly. That is why Dog must pass the name up through super(name). The superclass keeps control of its own data.
The first-line rule
A call to super(...) must be the first statement in a constructor. This code does not compile:
class Dog extends Animal {
private final String breed;
Dog(String name, String breed) {
this.breed = breed;
super(name); // compile error
}
}The reason is simple. The superclass part of the object must be ready before the subclass part uses it. Java enforces this order by requiring super(...) first.
Note that in recent Java versions, you can write some statements before super(...) as long as they do not use the object being built. Treat this as an advanced feature. As a beginner, put super(...) on the first line.
The hidden super() call
What if you never write super(...)? Java adds one for you. The compiler inserts a call to super() with no arguments as the first line of every constructor that does not start with super(...) or this(...).
class Vehicle {
Vehicle() {
System.out.println("Vehicle created");
}
}
class Car extends Vehicle {
Car() {
System.out.println("Car created");
}
}
public class Main {
public static void main(String[] args) {
new Car();
}
}The output is:
Vehicle created
Car createdThe Car constructor has no super() call written. Java inserts super(); at the top, so the Vehicle constructor runs first.
The same rule applies when a class declares no constructor at all. Java then creates a default constructor, which has no parameters and only calls super().
A common error: no matching super constructor
The hidden super() call causes the most common mistake with this topic. Look at this code.
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
Dog() {
// Java inserts super(); here
}
}This fails to compile. Animal has only one constructor, and it needs a String. The inserted super() has no arguments, so no constructor matches. The error message looks like this:
constructor Animal in class Animal cannot be applied to given types;There is a related trap. Once you declare any constructor in a class, Java no longer creates the default no-argument constructor for you. Animal above has no no-argument constructor for exactly this reason.
You have two fixes:
- Call a constructor that exists, such as
super("Unknown"). - Add a no-argument constructor to
Animal.
class Dog extends Animal {
Dog() {
super("Unknown");
}
}Chaining with this(...)
A class can have several constructors. One constructor can call another in the same class with this(...). This avoids repeating code.
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
Animal() {
this("Unknown");
}
String getName() {
return name;
}
}
class Dog extends Animal {
private final String breed;
Dog(String name, String breed) {
super(name);
this.breed = breed;
}
Dog(String name) {
this(name, "Mixed");
}
Dog() {
this("Unnamed");
}
String getBreed() {
return breed;
}
}
public class Main {
public static void main(String[] args) {
Dog a = new Dog();
Dog b = new Dog("Rex");
Dog c = new Dog("Fido", "Poodle");
System.out.println(a.getName() + " " + a.getBreed());
System.out.println(b.getName() + " " + b.getBreed());
System.out.println(c.getName() + " " + c.getBreed());
}
}The output is:
Unnamed Mixed
Rex Mixed
Fido PoodleFollow the call new Dog():
Dog()callsthis("Unnamed").Dog(String)callsthis(name, "Mixed").Dog(String, String)callssuper(name).Animal(String)stores the name.
Only one constructor in the chain calls super(...). The others use this(...).
The chain reaches the top: Object
Every class has a superclass. If you do not write extends, Java makes your class extend Object. So the chain always ends at the Object constructor. You never write that call yourself, because the compiler inserts it.
For new Dog() the full chain is Dog, then Animal, then Object. The constructors finish in the reverse order. Object finishes first, then Animal, then Dog.
Order of output
The order in which constructors finish matters when they print or change state. This example shows three levels.
class A {
A() {
System.out.println("A constructor");
}
}
class B extends A {
B() {
System.out.println("B constructor");
}
}
class C extends B {
C() {
System.out.println("C constructor");
}
}
public class Main {
public static void main(String[] args) {
new C();
}
}The output is:
A constructor
B constructor
C constructorThe C constructor starts first, but its first action is the call to B, which first calls A. The body of A runs first. Then the body of B, then the body of C.
Rules you can apply
| Situation | What Java does |
|---|---|
| Constructor starts with `super(args)` | Calls the matching superclass constructor |
| Constructor has no `super` or `this` call | Inserts `super()` as the first line |
| Class declares no constructor | Creates a default constructor that calls `super()` |
| Constructor starts with `this(args)` | Calls another constructor in the same class |
| Superclass has no no-argument constructor | Every subclass constructor must call `super(args)` or `this(args)` |
| Superclass constructor is `private` | A subclass in another top-level class cannot call it |
A warning about overridable methods
Avoid calling a method that a subclass can override from inside a constructor. The superclass constructor runs before the subclass fields are set up. An overridden method may then see fields that still hold default values.
class Base {
Base() {
describe();
}
void describe() {
System.out.println("Base");
}
}
class Derived extends Base {
private String label = "ready";
@Override
void describe() {
System.out.println("Label is " + label);
}
}
public class Main {
public static void main(String[] args) {
new Derived();
}
}The output is:
Label is nullThe Base constructor calls describe(). Dynamic dispatch picks the Derived version. But label has not been assigned yet, so it is still null. The next chapter looks at this order in more detail.
Summary of common mistakes
- Forgetting that constructors are not inherited, then calling
new Dog("Rex")whenDoghas no such constructor. - Putting
super(...)after another statement. - Declaring a constructor in the superclass and forgetting that the no-argument constructor is gone.
- Using both
this(...)andsuper(...)in one constructor. - Creating a loop, such as constructor A calling
this(...)on constructor B, which callsthis(...)on A. The compiler rejects this.
Exercise
Look at this code. Does it compile? If not, give two ways to fix it. class Shape { private final String color; Shape(String color) { this.color = color; } } class Circle extends Shape { private final double radius; Circle(double radius) { this.radius = radius; } }
Show answer
It does not compile. The Circle constructor has no super(...) call, so Java inserts super(). Shape has no no-argument constructor, so no match exists. Fix 1: in Circle, write super("red"); as the first line of the constructor, or change the constructor to take a color and pass it up with super(color). Fix 2: add a no-argument constructor to Shape, for example Shape() { this("none"); }.
Exercise
What does this program print? class P { P() { System.out.println("P"); } P(int x) { this(); System.out.println("P" + x); } } class Q extends P { Q() { super(5); System.out.println("Q"); } } public class Main { public static void main(String[] args) { new Q(); } }
Show answer
It prints P, then P5, then Q, each on its own line. Q() calls super(5), which runs P(int). That constructor first calls this(), which runs P() and prints P. Then P(int) prints P5. Finally the body of Q() prints Q.