For an assignment, we need to create a simplified BankAccount class with unique IDs for each object created from it. It would seem like the best means to do so would be a static int belonging to the class itself, but attempts to increment it are not increasing its value from 0. What mistake am I making here? I assume it's likely something trivial, but I can't seem to see it.
public class BankAccount {
// instance fields
/**
* each BankAccount instance should have
* a unique account number
*/
private int accountNumber;
private String accountHolder;
private double currentBalance;
private double overdraftLimit;
// static fields
private static int nextID;
// constructors
public void BankAccount(){
this.accountNumber = BankAccount.nextID++;
this.currentBalance = 0;
this.overdraftLimit = 0;
}
public void BankAccount(String accountHolder, double overdraftLimit){
this.accountNumber = BankAccount.nextID++;
this.currentBalance = 0;
this.accountHolder = accountHolder;
this.overdraftLimit = overdraftLimit;
}
}
I defined a main method solely to test the object definition; it's superfluous to the class itself. Any help would be greatly appreciated!
EDIT: For reference, not a duplicate of the other linked issue. This concerns a badly initialised constructor, not a for loop.
It's not the constructors
// this is method: 'bankAccountInstance.BankAccount()'
public void BankAccount()
{
this.accountNumber = BankAccount.nextID++;
//
}
// and this is method: 'bankAccountInstance.BankAccount("str", 5.1)'
public void BankAccount(String accountHolder, double overdraftLimit)
{
this.accountNumber = BankAccount.nextID++;
//
}
That are consturctors
// this is constructor 'BankAccount b = new BankAccount()'
public BankAccount()
{
this.accountNumber = BankAccount.nextID++;
//
}
// and this is constructor 'BankAccount b = new BankAccount("Account", 1.0)'
public BankAccount(String accountHolder, double overdraftLimit)
{
this.accountNumber = BankAccount.nextID++;
//
}
You can read more about constructors here
The problem is that what you think you've defined as constructors aren't constructors. They are just methods, and they aren't called ever. So Java inserted a default constructor, and by default it initialized your accountNumber to 0 always.
Change
public void BankAccount(){
public void BankAccount(String accountHolder, double overdraftLimit){
to
public BankAccount(){
public BankAccount(String accountHolder, double overdraftLimit){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With