0

I wrote the following code and driver program but I am not sure how to create bank account objects using both constructors. One constructor takes an initial balance and the second constructor opens an account with no money. Also, should the accountBalance include validity checks?

Optionally, I could do the following:

Include a fee as part of what describes a bank account. Update the BankAccount class as necessary. The user should be able to set the fee amount for each account and add the fee through a method. Add code to the driver program to demonstrate the fee functionality. (Could someone explain to me what this is asking)

//Bank Account class   
import java.text.NumberFormat;

public class BankAccount {

private String ownerName;
private String accountId;
private double accountBalance;

public BankAccount(String ownerName, String accountId, double accountBalance) {
    this.ownerName = ownerName;
    this.accountId = accountId;
    if(accountBalance >= 0) { 
        this.accountBalance = accountBalance;           
    } else {
        System.out.println("Due to your negative account balace, you will be issued a fee.\n");
    }
}

public BankAccount(double accountBalance) {
    accountBalance = 0;
}

public String getOwnerName() {
    return ownerName;
}

public void setOwnerName(String ownerName) {
    this.ownerName = ownerName;
}

public String getAccountId() {
    return accountId;
}

public void setAccountId(String accountId) {
    this.accountId = accountId;
}

public double getAccountBalance() {
    return accountBalance;
}

public void setAccountBalance(double accountBalance) {
    if(accountBalance >= 0) { 
        this.accountBalance = accountBalance;           
    } else {
        System.out.println("Due to your negative account balace, you will be issued a fee.\n");
    }
}

public void withdraw(double amount) { 
    if(amount > 0 && amount < accountBalance) { 
        accountBalance -= amount;           
    } else {
        System.out.println("Invalid withdraw amount! Please try again.\n");
    }
}

public void deposit(double amount) { 
    if(amount > 0) { 
        accountBalance += amount;
    } else {
        System.out.println("Invalid deposit amount! Please try again.\n");
    }
}

public String toString() { 
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
    return "Account Owner's Name: " + ownerName + "\n" + "Account ID: " + accountId + "\n" + 
           "Balance in the account: " + currencyFormatter.format(accountBalance);
}
}

//Driver Program
public class BankAccountDriver {

public static void main(String[] args) {

    BankAccount myAccount = new BankAccount("Smith", "123jahgsd", 1200);                      
    myAccount.withdraw(0.453);
    myAccount.deposit(1000.1);
    System.out.println(myAccount);
}
}
3
  • 1
    It's not clear what you're asking, but both of the constructors of BankAccount include an opening balance. You need to be really clear when asking a question - it should be specific, and only one question per post. Commented Feb 21, 2017 at 7:29
  • Also, should the accountBalance include validity checks? what type of checks? postive, zero, or negative balances are OK is my opinion Commented Feb 21, 2017 at 7:50
  • Just for the record: i updated the answer again to talk a bit about the validation topic of your question. Commented Feb 21, 2017 at 8:09

5 Answers 5

4

All nice answers, but they actually "miss" the "real" issue; and that is: you don't put down constructors because you can.

You create the code that is required to fulfill your requirements. In other words: you step back; and you think up respectively design the "intended use cases" for your bank account class.

And things to consider there: you avoid classes that can be created using such different paths.

Example: it is extremely dangerous to allow for empty id / owner fields. That leaves those fields with null values; and that means that you either need a lot of checking here and there; and if you forgot that here or there; you will run into NullPointerExceptions sooner or later (rather soon).

And keep in mind: your objects are meant to represent (model!) "reality". In reality, a bank account doesn't go without an owner; or an id.

In that sense, a sane implementation of your class would much more look like:

public class BankAccount {
  private final String owner;
  private final String id;
  private double currentBalance;

  public BankAccount(String owner, String id) {
    this(ownwer, id, 0);
  }

  public BankAccount(String owner, String id, double currentBalance) {
    this.owner = owner;
    ...

Notes here:

  • You want to prevent owner/id to be changed, so you make them final; and thus you also don't have setter methods for those fields
  • In a real world solution, you would not use Strings to represent names or ids, but distinct classes
  • You would also never ever use double to represent currency. This is a superbasic thing: money should not be represented using floating point numbers! (You would be looking towards to the BigDecimal class; or simply using int instead of double (and represent 1.75 $ as 175 cent)
  • And just a glance of real real world: nowadays, you don't model a bankaccount to have a "current balance". Instead, a bank account might be affiliated to a history of events (denoting deposits and pay-off transactions).

Final point: for your current exercise, that kind of "validation" for withdrawl/deposit is "okay"; in the "real world" validation would probably happen in many other places, too. (coming back to my initial statement: it all depends on your model; a simple model could say that a bank account itself is "validating" things; but a more realistic solution is that you have other components that deal with "rules", "laws" and all kinds of topics that do "validation").

Sign up to request clarification or add additional context in comments.

9 Comments

very good points, however maybe the owner should be able to change
Largely agreed; but I'd say a cleaner design than "telescoping" the constructors is just to have one constructor, taking the name and id. Then just use the deposit method afterwards to set the balance.
Understood! Thank you for clarifying that confusion:)
@ScaryWombat Maybe for this exercise here; but well; in the real world, bank accounts do not change owners. You move money from one account to another, but not the whole account.
@ScaryWombat Well, that is where "how to model" the owner kicks in. Actually you would not use the "owner name", but some "owner id" field there; and that should be definitely be final ;-)
|
1

You can do like this:

   public BankAccount(String ownerName, String accountId, double accountBalance) {
       this.ownerName = ownerName;
       this.accountId = accountId;
       this.accountBalance = accountBalance;
   }

   public BankAccount() {
       this("some default name", "some default id", 0.0);
   }

Comments

1

If you want to create a BankAccount with a zero balance then

public BankAccount(String ownerName, String accountId, double accountBalance) {
    this.ownerName = ownerName;
    this.accountId = accountId;
    this.accountBalance = accountBalance;
}

public BankAccount() {
    this.accountBalance = 0;
}

You can instantiate them as

BankAccount mine = new BankAccount("Scary", "123", 1000000.00);
BankAccount empty = new BankAccount();

edit

If you choose to construct a method with the second method, the id and owner would also be null and maybe not very useful

2 Comments

"with zero balance" yes, but that also creates it with null id and owner name.
@AndyTurner Agree not very useful. I have updated my answer to reflect this.
1

You can't create one bank account object using both constructors. You only call one of the two constructors to create a new object. So you either do:

BankAccount account = new BankAccount("Sweeper", "ABCDEF", 10000);

or:

BankAccount account = new BankAccount(100000);

Note that your second constructor's parameter is pointless because you initialize the balance to 0 no matter what the parameter is:

public BankAccount(double accountBalance) {
    accountBalance = 0;
}

I think this makes more sense:

public BankAccount() {
    this.accountBalance = 0;
}

As for your second question, I will give you some tips.

You need to add a new field to the class, called fee. Add getters and setters for it.

2 Comments

You are the only one that answered How to create objects using more than one constructor?
I guess I was confused about the requirements that: One constructor takes an initial balance and the second constructor opens an account with no money. I thought that I had to initialize the balance to zero.
1

You make objects depending on which constructor you want to use. For example, to use the first constructor you need three parameters like so,

BankAccount first = new BankAccount("Bob", "ID45", 400.50);

and to use the second constructor you only need one parameter, the balance, like so,

BankAccount second = new BankAccount(400.50);

They'll both make instances of BankAccount except the difference is that on creation, the first bank account will have fields ownerName and accountId filled out while the second bank account will have those fields set to empty String values. However, the second object will have a balance of 0 unlike the first object's balance of 400.5

EDIT: Like user ScaryWombat suggested, there is a flaw in your second constructor because if you want to define an object with a balance of 0 then there's no point in adding a balance parameter. Also, in this case it would be advisable to give default values to your other fields as well,

public BankAccount() {
    ownerName = "unknown";
    accountId = "unknown";
    accountBalance = 0;
}

So now when you create an instance of BankAccount with this constructor, it'll have the default values, "unknown", "unknown", and 0.

BankAccount third = new BankAccount();

Also, for the fee part, all you have to do is not only create another field in your BankAccount class called fee but also make a setter method to allow the user to set its fee,

private double fee;
.
.
.
public void setFee (double fee) {
   this.fee = fee;
}

And in the main method, the user can access it with the following,

BankAccount account = new BankAccount("Fred", "ID145", 400);
account.setFee(15); //this will set the fee to 15

5 Comments

@ally This is correct. However, I might add that your second constructors parameter is pointless. You are setting account balance to 0. Why put a parameter there?
@RSon1234 true just edited my answer to reflect that.
This is bad behavior to have BankAccount second = new BankAccount(400.50); and then have the accountBalance being 0
@ScaryWombat True, but this is how OP defined the constructor, not Chris
@ScaryWombat good point I edited my answer to make note of this. Thank you for the suggestion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.