.NET Core  

Real time Example of Constructor Chaining

Constructor is a special type of function that is automatically called by creating an instance of a class. A Constructor has multiple constructor functions within a class that are overloading, and static constructors are initialized by static members of a class. If Constructors is not defined, the compiler will declare Constructors; it does not have any return type.

Constructor Chaining is calling one constructor from another constructor. This process reuses code and reduces redundancy. Two ways of syntax are there using the chaining process, given below

Call a Constructor in the base class.

public ClassName() : base() { }

Call another constructor in the same class.

public ClassName() : this() { }

Real-time examples for constructor chaining with BankAccount class constructors are given here. Constructor overloading concept will be used to call the same class constructor by using 'this' keyword.

class BankAccount {
    String accountHolder;
    String accountType;
    double balance;

    // Default constructor
    public BankAccount() {
        this("Unknown", "Savings", 0.0); // Constructor chaining
    }

    // Constructor with accountHolder
    public BankAccount(String accountHolder) {
        this(accountHolder, "Savings", 0.0); // Constructor chaining
    }

    // Constructor with accountHolder and accountType
    public BankAccount(String accountHolder, String accountType) {
        this(accountHolder, accountType, 0.0); // Constructor chaining
    }

    // Full constructor
    public BankAccount(String accountHolder, String accountType, double balance) {
        this.accountHolder = accountHolder;
        this.accountType = accountType;
        this.balance = balance;
    }

    public void displayDetails() {
        System.out.println("Account Holder: " + accountHolder);
        System.out.println("Account Type: " + accountType);
        System.out.println("Balance: " + balance);
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount();
        BankAccount account2 = new BankAccount("aaa");
        BankAccount account3 = new BankAccount("bbb", "Current");
        BankAccount account4 = new BankAccount("cccc", "Savings", 5000.0);

        account1.displayDetails();
        account2.displayDetails();
        account3.displayDetails();
        account4.displayDetails();
    }
}

Output

Account Holder: Unknown
Account Type: Savings
Balance: 0.0

Account Holder: aaa
Account Type: Savings
Balance: 0.0

Account Holder: bbb
Account Type: Current
Balance: 0.0

Account Holder: cccc
Account Type: Savings
Balance: 5000.0