package bank; /** * A bank account object encapsulates the account number, owner name, and * current balance of a bank account. * This version checks for illegal method and constructor arguments. */ public class BankAccount { private int number; private String name; private double balance; /** * Construct a bank account with given account number, * owner name and initial balance. * @param accountNumber the account number * @param ownerName the account owner name * @param initialBalance the initial account balance * @throws IllegalArgumentException if account number is negative, * owner name is null or empty, or if balance is negative. */ public BankAccount(int accountNumber, String ownerName, double initialBalance) { if (accountNumber <= 0) throw new IllegalArgumentException("Account number must be positive"); if (ownerName.equals("") || ownerName == null) throw new IllegalArgumentException("Owner name not defined"); if (initialBalance < 0) throw new IllegalArgumentException("Balance must be non-negative"); number = accountNumber; name = ownerName; balance = initialBalance; } /** * Deposit money in the account. * @param amount the deposit amount. If amount <= 0 the * account balance is unchanged. * @throws IllegalArgumentException if deposit amount is negative */ public void deposit(double amount) { if (amount < 0) throw new IllegalArgumentException("Invalid amount for deposit"); balance = balance + amount; } /** * Withdraw money from the account. * If account would be overdrawn the account balance is unchanged. * @param amount the amount to withdraw. * @throws IllegalArgumentException if withdraw amount is invalid */ public void withdraw(double amount) { if (amount < 0 || amount > balance) throw new IllegalArgumentException("Invalid amount for withdraw"); balance = balance - amount; } /** * Return the account number. * @return the account number. */ public int getNumber() { return number; } /** * Return the owner name. * @return the owner name. */ public String getName() { return name; } /** * Return the account balance. * @return the account balance. */ public double getBalance() { return balance; } /** * string representation of this account. * @return string representation of this account. */ public String toString() { return "BankAccount[" + number + ", " + name + ", " + balance + "]"; } }