Home > Net >  How many times is a constructor called when it's overloaded?
How many times is a constructor called when it's overloaded?

Time:10-29

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?

CodePudding user response:

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.

CodePudding user response:

The this() refers to a constructor of the class itself. You can use this() to call the constructor from within the class. In your example, your constructor of signature BankAccount() can be referred from within the class as this() and BankAccount(double, double) from this(double, double) signatures. When you instantiate a BankAccount object with BankAccount() it calls the BankAccount(double, double) which increments numberOfAccounts. Then your caller BankAccount() also increments numberOfAccounts. To fix this, simply remove this(0,0) from the first constructor. You do not need to initialize the members to 0 because Java does that for you

  • Related