Skip to content
Advertisement

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

BankAccount.java

JavaScript

Test.java

JavaScript

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:

JavaScript

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