Menu
Coddy logo textTech

Constructor Chaining

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 23 of 87.

Constructor chaining is the process of calling one constructor from another. This technique helps avoid code duplication when a class has multiple constructors or when working with inheritance hierarchies.

Within the same class, you can chain constructors using this(). This lets you have one "main" constructor that does all the work, while other constructors simply delegate to it:

public class Rectangle {
    private int width;
    private int height;
    
    public Rectangle() {
        this(1, 1);  // Calls the two-parameter constructor
    }
    
    public Rectangle(int size) {
        this(size, size);  // Creates a square
    }
    
    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
}

In inheritance, constructor chaining happens automatically. When you create a subclass object, Java calls the parent constructor first using super(). If you don't explicitly call super(), Java inserts super() (the no-argument version) automatically:

public class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
        System.out.println("Animal constructor");
    }
}

public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name);  // Must be first line
        this.breed = breed;
        System.out.println("Dog constructor");
    }
}

Creating new Dog("Buddy", "Labrador") prints "Animal constructor" first, then "Dog constructor". This ensures parent classes are always properly initialized before the child class adds its own setup.

challenge icon

Challenge

Easy

Let's build a product ordering system that demonstrates constructor chaining both within a class and across an inheritance hierarchy. You'll see how this() chains constructors in the same class, while super() chains to parent constructors.

You'll create three files to organize your code:

  • Product.java: Create a parent class representing any product in a store. It should have:
    • Private fields for name (String) and price (double)
    • A main constructor that takes both name and price, initializes the fields, and prints: Product constructor: [name]
    • A second constructor that takes only the name and chains to the main constructor using this(name, 0.0) to set a default price of 0.0
    • Methods getName() and getPrice() to access the fields
  • Electronics.java: Create a subclass that extends Product and adds warranty information:
    • A private field for warrantyYears (int)
    • A main constructor that takes name, price, and warrantyYears - use super(name, price) to initialize the parent, then set the warranty and print: Electronics constructor: [warrantyYears] year warranty
    • A second constructor that takes only name and price, chaining to the main constructor with this(name, price, 1) to provide a default 1-year warranty
    • A third constructor that takes only the name, chaining to the second constructor with this(name, 0.0)
    • A method getDetails() that returns: [name] - $[price] ([warrantyYears] year warranty)
  • Main.java: Demonstrate the constructor chaining in action. You'll receive three inputs: a product name (String), price (double), and warranty years (int). Create an Electronics object using all three parameters, then print the result of getDetails().

You will receive three inputs: the product name, price, and warranty years.

Format the price in getDetails() to show 2 decimal places using String.format("%.2f", price). Watch the output carefully - you'll see the constructor messages appear in order, showing how the chain flows from parent to child!

Cheat sheet

Constructor chaining is the process of calling one constructor from another to avoid code duplication.

Chaining Within the Same Class

Use this() to call another constructor in the same class:

public class Rectangle {
    private int width;
    private int height;
    
    public Rectangle() {
        this(1, 1);  // Calls the two-parameter constructor
    }
    
    public Rectangle(int size) {
        this(size, size);  // Creates a square
    }
    
    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
}

Chaining in Inheritance

Use super() to call the parent class constructor. It must be the first line in the constructor:

public class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
        System.out.println("Animal constructor");
    }
}

public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name);  // Must be first line
        this.breed = breed;
        System.out.println("Dog constructor");
    }
}

If you don't explicitly call super(), Java automatically inserts super() (the no-argument version). Parent constructors are always called before child constructors, ensuring proper initialization order.

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read inputs
        String name = scanner.nextLine();
        double price = scanner.nextDouble();
        int warrantyYears = scanner.nextInt();
        
        // TODO: Create an Electronics object using all three parameters
        
        // TODO: Print the result of getDetails()
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming