ISF DP Computer Science

OOP Review #


BankAccount #

Refer to the following class to answer the questions on your worksheet.

import java.io.*;
import java.util.*;

public class BankAccount {
    private static double interestRate = 5.00; // Static variable
    private static int nextAccountNumber = 1001; // Static variable
    private String name;
    private double balance;
    private int accountNumber;

    public BankAccount(String name) {
        this.name = name;
        this.balance = 0;
        // Use the class name as a prefix to access the static variables
        this.accountNumber = BankAccount.nextAccountNumber;
        BankAccount.nextAccountNumber++;
    }

    public void deposit(double amount) {
        this.balance += amount;
    }

    public boolean withdraw(double amount) {
        if (this.balance < amount) {
            return false;
        }
        this.balance -= amount;
        return true;
    }

    public boolean transfer(double amount, BankAccount recipient) {
        if (this.withdraw(amount)) {
            recipient.deposit(amount);
            return true;
        }
        return false;
    }

    public void applyInterest() {
        // balance is an instance variable, interestRate is a static variable
        this.balance += this.balance * (BankAccount.interestRate / 100);
    }

    public double getBalance() {
        return this.balance;
    }

    public String getName() {
        return this.name;
    }

    public String toString() {
        return "Account " + this.accountNumber + ": " + this.name + " has balance $" + this.balance);
    }

    public static BankAccount find(BankAccount[] accounts, String name) {
        BankAccount foundAccount = null;
        boolean found = false;
        for (int i = 0; i < accounts.length && !found; i++) {    
            if (accounts[i].getName().equals(name)) {
                foundAccount = accounts[i];
                found = true;
            }
        }
        return foundAccount; // returns the account if found, otherwise null
    }
}