Menu
Constructor Chaining
The first line of every constructor must be either—
- A this() call to another constructor in the same class.
- A super() call to a superclass constructor.
If no constructor call is written as the first line of a constructor, the compiler automatically inserts a call to the parameter-less superclass constructor.
Example 1
Below is an example of demonstrating constructor chaining.
ConstructorChain.java
public class ConstructorChain {
public static void main(String[] args) {
Child c = new Child();
}
}
class Child extends Parent {
Child() {
System.out.println("Child() constructor");
}
}
class Parent extends Grandparent {
Parent() {
this(30);
System.out.println("Parent() constructor");
}
Parent(int x) {
System.out.println("Parent(" + x + ") constructor");
}
}
class Grandparent {
Grandparent() {
System.out.println("Grandparent() constructor");
}
}
Output:
Grandparent() constructor
Parent(30) constructor
Parent() constructor
Child() constructor
Example 2
See another example of constructor chaining.
SpecialCube.java
class Cube {
int length, breadth, height;
public int getVolume() {
return (length * breadth * height);
}
Cube() {
this(10, 10);
System.out.println("Default Cube Constructor");
}
Cube(int l, int b) {
this(l, b, 10);
System.out.println("Cube Constructor having 2 parameters");
}
Cube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Cube Constructor having 3 parameters");
}
}
public class SpecialCube extends Cube {
int weight;
SpecialCube() {
super();
weight = 10;
}
SpecialCube(int l, int b) {
this(l, b, 10);
System.out.println("SpecialCube Constructor having 2 parameters");
}
SpecialCube(int l, int b, int h) {
super(l, b, h);
weight = 20;
System.out.println("SpecialCube Constructor having 3 parameters");
}
public static void main(String[] args) {
SpecialCube obj1 = new SpecialCube();
SpecialCube obj2 = new SpecialCube(10, 20);
System.out.println("Volume of SpecialCube1: " + obj1.getVolume());
System.out.println("Weight of SpecialCube1: " + obj1.weight);
System.out.println("Volume of SpecialCube2: " + obj2.getVolume());
System.out.println("Weight of SpecialCube2: " + obj2.weight);
}
}
Output:
Cube Constructor having 3 parameters
Cube Constructor having 2 parameters
Default Cube Constructor
Cube Constructor having 3 parameters
SpecialCube Constructor having 3 parameters
SpecialCube Constructor having 2 parameters
Volume of SpecialCube1: 1000
Weight of SpecialCube1: 10
Volume of SpecialCube2: 2000
Weight of SpecialCube2: 20
Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.