Question

How to Call One Constructor from Another in Java

javaconstructor

Question

In Java, is it possible to call one constructor from another constructor within the same class, rather than from a subclass? If so, how is this done? Also, if there are multiple ways to do it, what is the best approach?

Short Answer

By the end of this page, you will understand how constructor chaining works in Java, how to call one constructor from another using this(...), when super(...) is involved, and how to design constructors that avoid duplicated initialization logic.

Concept

In Java, a constructor can call another constructor to reuse initialization code. This is called constructor chaining.

When multiple constructors exist in the same class, they often share part of their setup logic. Instead of repeating that code in every constructor, one constructor can delegate to another.

Java provides a special syntax for this:

this(...)

This calls another constructor in the same class.

For example, if one constructor accepts full details and another accepts only partial details, the shorter constructor can call the more complete one and provide default values.

This matters because it helps you:

  • reduce duplicated code
  • keep initialization consistent
  • make classes easier to maintain
  • avoid bugs caused by forgetting to initialize fields in one constructor

There is also a related constructor call:

super(...)

This calls a constructor in the parent class, not the same class.

A key Java rule is that a constructor call using this(...) or super(...) must be the first statement in the constructor.

So the main answer is: yes, you can call one constructor from another in the same class by using this(...), and this is the standard and best approach.

Mental Model

Think of constructors like different reception desks for entering the same building.

  • One desk asks for full information.
  • Another desk asks for only the basics.
  • Instead of each desk doing all the paperwork separately, the simpler desk forwards the visitor to the main desk with some default values.

That forwarding step is what this(...) does.

So:

  • this(...) = send the work to another constructor in the same class
  • super(...) = send the work to a constructor in the parent class

This keeps all the main setup in one place.

Take Quiz

Syntax and Examples

Core syntax

To call another constructor in the same class:

public ClassName(...) {
    this(...);
}

To call a parent constructor:

public ClassName(...) {
    super(...);
}

Only one of these can appear, and it must be the first line of the constructor.

Example: constructor chaining with this(...)

public class User {
    private String name;
    private int age;

    public User() {
        this("Anonymous", 0);
    }

    public User(String name) {
        this(name, 0);
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

What this does

  • User() calls User(String, int) with default values.
  • User(String) also calls User(String, int).
  • The full constructor does the actual field assignment.

This is a common and clean pattern.

Example usage

User u1 = new User();
User u2 = new User("Maya");
User u3 = new User("Maya", 25);

All three objects are initialized through the same final constructor logic.

Example with super(...)

class Person {
    protected String name;

    public Person(String name) {
        this.name = name;
    }
}

class Employee extends Person {
    private int employeeId;

    public Employee(String name, int employeeId) {
        super(name);
        this.employeeId = employeeId;
    }
}

Here, super(name) calls the parent constructor. It is not constructor chaining within the same class; it is inheritance-based initialization.

Step by Step Execution

Traceable example

public class Product {
    private String name;
    private double price;

    public Product() {
        this("Unknown", 0.0);
    }

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
}

Now imagine this code runs:

Product p = new Product();

Step by step

  1. Java sees new Product().

  2. It enters the no-argument constructor:

    public Product() {
        this("Unknown", 0.0);
    }
    
  3. The this("Unknown", 0.0) call transfers control to the other constructor in the same class.

  4. Java enters:

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
    
  5. this.name = name; sets name to "Unknown".

  6. this.price = price; sets price to 0.0.

  7. The second constructor finishes.

  8. Control returns, and the object is fully created.

Result

The object p contains:

  • name = "Unknown"
  • price = 0.0

Important rule to notice

This would be invalid:

public Product() {
    System.out.println("Creating product");
    this("Unknown", 0.0); // Error
}

Why? Because this(...) must be the first statement in the constructor.

Real World Use Cases

Constructor chaining is useful whenever a class can be created in multiple ways.

Common examples

  • User accounts: create a user with full details, or create one with only a username and use defaults for the rest
  • Configuration objects: allow a simple constructor for common settings and a full constructor for advanced settings
  • Data models: create an object from partial data during testing, but full data in production
  • API clients: provide a constructor with default timeout values and another with custom timeout values
  • File or database settings: one constructor may use standard paths or ports, while another accepts explicit values

Example: API client defaults

public class ApiClient {
    private String baseUrl;
    private int timeout;

    public ApiClient(String baseUrl) {
        this(baseUrl, 5000);
    }

    public ApiClient(String baseUrl, int timeout) {
        this.baseUrl = baseUrl;
        this.timeout = timeout;
    }
}

This lets developers choose between a simple setup and a more detailed one without duplicating code.

Take Quiz

Real Codebase Usage

In real projects, developers often use constructor chaining to centralize object initialization.

Common patterns

1. Default values

A smaller constructor supplies default values to a larger one.

public Logger(String name) {
    this(name, "INFO");
}

2. Validation in one place

Instead of validating inputs in every constructor, developers usually send all constructors to one main constructor.

public class Account {
    private String email;
    private boolean active;

    public Account(String email) {
        this(email, true);
    }

    public Account(String email, boolean active) {
        if (email == null || email.isBlank()) {
            throw new IllegalArgumentException("email cannot be empty");
        }
        this.email = email;
        this.active = active;
    }
}

3. Avoiding repeated setup code

Without chaining, repeated assignments and validation can spread across constructors and become hard to maintain.

4. Pairing with static factory methods

In larger codebases, constructors may be kept small and simple, while named creation methods give clarity.

public static Account guestAccount() {
    return new Account("guest@example.com", false);
}

5. Guarding against inconsistent state

If every constructor initializes fields separately, one constructor may accidentally forget an important field. Chaining reduces that risk.

Common Mistakes

1. Forgetting that this(...) must be first

Broken code:

public User() {
    System.out.println("Creating user");
    this("Anonymous");
}

Why it fails:

  • Java requires this(...) to be the very first statement.

Correct version:

public User() {
    this("Anonymous");
}

2. Trying to use both this(...) and super(...)

Broken code:

public Employee() {
    this("Unknown");
    super();
}

Why it fails:

  • Only one constructor call can be first.
  • You cannot call both directly in the same constructor.

3. Creating an infinite constructor loop

Broken code:

public class Example {
    public Example() {
        this(1);
    }

    public Example(int x) {
        this();
    }
}

Why it fails:

  • Each constructor calls the other forever.
  • Java detects this as recursive constructor invocation.

4. Duplicating logic instead of chaining

Less ideal:

public User() {
    name = "Anonymous";
    age = 0;
}

public User(String name) {
    this.name = name;
    age = 0;
}

Better:

public User() {
    this("Anonymous", 0);
}

public User(String name) {
    this(name, 0);
}

5. Confusing this with this(...)

  • this.name refers to the current object's field.
  • this(...) calls another constructor.

These are related but different uses of this.

Comparisons

this(...) vs super(...)

Featurethis(...)super(...)
Calls constructor inSame classParent class
Used forConstructor chainingInheritance initialization
Must be first statementYesYes
Can both be used in same constructorNoNo

Constructor chaining vs duplicated constructor logic

ApproachProsCons
Constructor chainingLess duplication, easier maintenance, consistent initializationRequires planning constructor flow
Repeated logic in each constructorSimple at first for tiny classesEasy to create bugs and inconsistencies

Constructors vs static factory methods

ApproachBest forNotes
ConstructorsDirect object creationGood for straightforward initialization
Static factory methodsNamed creation patternsCan be more readable for special cases

Example:

public static User guest() {
    return new User("Guest", 0);
}

Static factory methods do not replace constructor chaining; they often use it.

Take Quiz

Cheat Sheet

Quick rules

  • Use this(...) to call another constructor in the same class.
  • Use super(...) to call a constructor in the parent class.
  • this(...) or super(...) must be the first statement in a constructor.
  • You can use only one of them in a constructor.
  • Constructor chaining helps avoid duplicated initialization code.

Basic pattern

public class Example {
    public Example() {
        this("default");
    }

    public Example(String value) {
        // main initialization
    }
}

Best practice

  • Put the main initialization in one constructor.
  • Let smaller constructors pass default values to it.
  • Keep validation in one place when possible.

Common errors

// Error: not first statement
public Example() {
    int x = 1;
    this("test");
}
// Error: recursive constructor call
public Example() {
    this(1);
}

public Example(int x) {
    this();
}

Remember

  • this.field = current object's field
  • this(...) = another constructor in the same class

FAQ

Can you call one constructor from another in Java?

Yes. Use this(...) inside a constructor to call another constructor in the same class.

What is constructor chaining in Java?

Constructor chaining is the process of one constructor calling another constructor to reuse initialization logic.

What is the difference between this(...) and super(...) in Java?

this(...) calls a constructor in the same class. super(...) calls a constructor in the parent class.

Why must this(...) be the first statement?

Java requires object construction to begin with a constructor call before other setup code runs.

Can a constructor call both this(...) and super(...)?

No. Only one constructor call can appear, and it must be first.

What is the best way to organize multiple constructors?

Usually, put the full initialization logic in one main constructor and have smaller constructors call it with default values.

Is constructor chaining better than repeating code?

In most cases, yes. It reduces duplication and makes initialization more consistent.

What happens if constructors call each other in a loop?

That creates recursive constructor invocation, which is invalid and causes a compile-time error.

Take Quiz

Mini Project

Description

Create a small Book class that can be initialized in several ways: with no values, with only a title, or with a title and page count. This project demonstrates constructor chaining with this(...) so that all object setup happens in one place.

Goal

Build a Java class that uses constructor chaining to provide default values and avoid duplicated initialization code.

Requirements

  • Create a Book class with title and pages fields.
  • Add a no-argument constructor that uses default values.
  • Add a constructor that accepts only the title.
  • Add a constructor that accepts both title and pages.
  • Use constructor chaining so only one constructor performs the field assignments.
  • Print a few Book objects to verify the values.
Take Quiz

Keep learning

Related questions

View more