Skip to content
Advertisement

How many times is a constructor called when it’s overloaded?

BankAccount.java

public class BankAccount {
    private double checkingBalance;
    private double savingBalance;
    private static int numberOfAccounts;

    public BankAccount() {
        this(0, 0);
        numberOfAccounts++;
    }
    public BankAccount(double checkingInitial, double savingInitial) {
        this.checkingBalance = checkingInitial;
        this.savingBalance = savingInitial;
        numberOfAccounts++;
    }

    public static int getNumberOfAccounts() {
        return numberOfAccounts;
    }

Test.java

public class Test {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount(50, 50);
        BankAccount account2 = new BankAccount(100, 80);
        BankAccount account3 = new BankAccount();

        System.out.println("number of accounts is " + BankAccount.getNumberOfAccounts());

I should get number of accounts is 3 but I’m getting 4. If I instantiate all accounts with the parametrized constuctor, I get 3. If I add BankAccount account4 = new BankAccount();, I get 6. Is the default constructor called twice?

Advertisement

Answer

This is your problem:

public BankAccount() {
    this(0, 0);
    numberOfAccounts++; // <<<<<
}

The explicit call to the other constructor BankAccount(double, double) increments numberOfAccounts. Then you increment it again.

Delete the line marked ‘<<<<‘.

In answer to the question in the title:

How many times is a constructor called when it’s overloaded?

There is an explicit call to a constructor in your main program – so ‘once’. But you then wrote code in that constructor to call another constructor. That is entirely under your control.

Advertisement