Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading