Page 1 of 1

Banking System - Commonly Asked Commonly Asked Object Oriented Banking Design Rate Topic: ***** 3 Votes

#1 DaneAU  Icon User is offline

  • Great::Southern::Land
  • member icon

Reputation: 284
  • View blog
  • Posts: 1,617
  • Joined: 15-May 08

Post icon  Posted 22 April 2009 - 12:52 AM

I often find myself answering questions about Accounts, Clients and Banking systems in the java section as it seems to be the flavour of the times to demonstrate object oriented programming in both java and c++, so i thought to cut down on myself rewriting answers to common questions i would create a basic tutorial of how to setup a banking program utilising a few classes, some basic member functions(sometimes called methods) in order to demonstrate how to produce a functional program and replicate a basic banking system.

So to being with when we talk about a program for banking there are some very simple objects or classes that we will need to develop in order to implement a working object oriented design. Lets get one thing straigh to begin with, i often see people coding input and output within sub classes and i tend to steer clear of this (will explain what i mean later on).

When i think about a banking system and think... hmm how am i best going to achieve a managable program that has the ability to be extended if need be. I say this because often universities/schools/colleges work on a progressive nature, for instance they may start your projects off by getting you to create a basic class such as Person then ask you later on to implement another class such as Grades which may implement and make use of the Person class you previously have written. This is why it is important to make sure you document classes throughourly and make sure that they can be used later on in harder projects with ease of portability.

Ok - enough of all that, a banking system for the purposes of this tutorial will consist of 3 classes. In essence there are 3 Objects we need to describe and implement to function correctly as an Object Oriented design, firstly we have you / i as the Client - the client is our first class and it will describe essentially the person in the situation who has an Account - which is our 2nd class - then funnily enough that Account is part of yet a bigger Object called a Bank. So through the flow of that paragraph you can clearly see the order in which classes are derived by breaking down a large object (Bank) into its smaller objects or structures.

Just recapping the classes we need to develop are
- Client
- Account
- Bank


Client class
So lets get started on the Client class
Some basic things a client will have might be First Name, Last Name and perhaps some kind of contact details such as an addess.. well for this example the contact detail we will use breifly is a phone number. So we now know that our client needs some private varibiables (we use private to keep them secret from other objects in our banking system).


So we can begin writing our basic class - it would look something like this at early stages
class Client
{
        private String name_first, name_last;
        private long phone_number;
         
        //default constructor //
        Client() {}
}



now to keep things simple we will omit the use of our phone_number variable and just assign a default to it as it will keep things a little more condensed for later on (you may implement it on your own). So there we have a framework of our base class so how about some member functions(methods) to do some manipulation on our object/class, how about an overloaded constructor ? So we can create and object and pass values into the overload constructor... good idea i say

So we might wish to change phone numbers later on or we may wish to change names ? People get married right... so things need to be flexible. So how about we create some functions to change our variables should we need to at a later time. Notice all variables are private... this is good practice and you should try to do this and leave retrieving/changing them to functions such as the ones below GetName(); and changeFirstName(String n_new). Anyway with all that in mind we need to include perhaps some functions such as getName to return the name, change name... need 2 - one to change first and one to change last name... then because we have some contact details we could make use of a function to change / retrieve that detail. Anyway below is the full code for a client class.. It contains some basic functions (although not all are used in this example - they should be produced just in case later on you need to access /change them).

public class Client {

    private String name_first, name_last;
    private long phone_contact;
   
    // default constructor
    Client()    {}

    // Overload Constructor
    Client(String name_f, String name_lst)
    {
        name_first = name_f;
        name_last = name_lst; 
        
        // this is here for example only 
        // it is up to you to implement functions
        // to set / change this value through banking
        // program. A basic function is included below
        //
        phone_contact = 999999;
    }

    // method to return full name
    String getName()
    {
        return (name_first + " " + name_last);
    }

    void changeFirstName(String n_new)
    {
        name_first = n_new;
    }

    void changeLastName(String n_new)
    {
        name_last = n_new;
    }

    void change_phone_number(long p_number)
    {
        phone_contact = p_number;
    }

    long getPhoneNumber()
    {
        return phone_contact;
    }    
}



Now we have a basic Client class we are able to actually create an Account class which will be linked to our Client class simply because an Account always has an Account Holder (in our case we call the Account Holder a Client).

Account

As above we created a simple Framework of a class and began adding functions / variables as we moved through the design process. With the Account class the same principles of Object Oriented design carry through and in this class we will see an example of how our Client class is to be used. Remember keep variables private and only give access to them through functions (methods). Before we begin lets just draft a few things an Account must have
Firstly it must have an Account Balance, for this case the best option is to use a double to store this, it must also have a Client - or account name so that we are able to see the owner of the Account... Also there are a few basic things people do with accounts, most of all people Deposit money into them or Withdraw money from them. We will not delve into interest rates / withdrawal charges for now, i may explain some simple ways of implementing this at the conclusion of this tutorial.

So we have a basic structure for a class such as this.
public class Account
{
    private Client person;                 // account holders client
    private double balance;              // current account balance
    private long account_number;      // account number

    Account() {}
}


Ok obviously thats of no use to us so we must begin to implement some functions and an overloaded constructor to make this class/object useful to our Banking System.

So how about an overloaded constructor, allowing us to set an initial balance, an account number and the Client... Yep great idea
Account( Client c_client, double c_balance, long c_num)
{
        person = c_client;
        balance = c_balance;
        account_number = c_num;
}



Alright so thats all set, we pass a Client c_client, balance c_balance and account numberc_num to create our initial Account object. Now what do we do with it ? Oh thats right we will need some functions or methods to change the data we store in it, some obvious ones are deposit_funds(double p_amount); and withdraw_funds(double p_amount); ok so lets look into these two carefully because there is some things we must consider... when we deposit funds, there is no issues however what if we attempt to draw more funds than the balance actually has ? say balance is $5 and we try to withdraw $ 10 ? Do we allow the Client to go into negative balance or do we dissallow it ? The choice is up to you however i have chosen to dissallow it, subsequently i need to actually return a value from my withdraw function to let the Bank know if the process is allowed or dissallowed. So my deposit function looks like the following
// Function to deposit funds into an account //
public void deposit_funds( double p_amount)
{
      balance += p_amount;
}



Which is relatively straight forward, all we do is add p_amount which is our amount to be deposited to the balance of the account, notice it is also a void function whereas the withdraw function must let the Bank know if the transaction is legal... How about if we return an Integer ? 0 when the withdrawal can occur and -1 when it cannot, that will solve some problems however we must document it so we know whats going on.
public int withdraw_funds( double p_amount)
{
        // check if enough funds
        if ( p_amount > balance )
            return -1;
        else
            balance -= p_amount;
        return 0;
}


Ok so when the amount to withdraw exceeds our balance we know it cannot be done so we return -1 and if its less than balance we can proceed. Thats sorted so we must document the function and explain what is occuring...

Ok so some other functions / methods we will need at some point in our Account class could include the following
getName();   // return Account holders name
get_balance();  // return balance of account
get_account_number();  // return account number
getClient();  // return client



Ok so lets implement them into the class
public class Account
{
    // variables contained within class account //
    // accessible only via methods/functions as //
    // they are private and subsequently can    //
    // only be changed via member functions.    //

    private Client person;            // account holders client
    private double balance;           // current account balance
    private long account_number;      // account number

    // Constuctor for Objects of type account //
    Account( Client c_client, double c_balance, long c_num)
    {
        person = c_client;
        balance = c_balance;
        account_number = c_num;
    }

    // Function to deposit funds into an account //
    public void deposit_funds( double p_amount)
    {
        balance += p_amount;
    }

    // function to withdraw funds from an account //
    // checks to see whether funds are available. //
    public int withdraw_funds( double p_amount)
    {
        // check if enough funds
        if ( p_amount > balance )
            return -1;
        else
            balance -= p_amount;
        return 0;
    }

    // returns account balance //
    public double get_balance()
    {
        return balance;
    }

    // returns account holders name //
    public String get_name()
    {
        // Access our client object (person)
        // then access getName() function
        // of Client class
        return person.getName();
    }

    // returns account number //
    public long get_account_number()
    {
        return account_number;
    }

    public Client getClient()
    {
        return person;
    }

}




Alright so we now have a full Account class ready and rearing to go. Just a few things to note, you may notice that inside the function String get_name() we have the statement return peron.getName(); , what happens here is we are accessing the Client object we created in our constructor and in turn we are able to access functions from within the Client class i.e getName() is not a function of Account class rather it is a function of the Client class. person is our Client object within Account class, hence why we use person. when we wish to access any of the public functions of the Client class, for instance if we wished to get a Client's phone number from within the Account class we could use person.getPhoneNumber(); and so on for all the functions we created in the Client class.

Now that we have our Client and Account class setup and ready for a Bank to use, how about we create our own Bank and begin stealing peoples money through fees and charges - ahh but we don't do that in this bank - if you want to do such a thing you may create your own functions and edit the classes to do so :)

Bank
So All our program flow and structure will be done from our Bank class - also our Bank class will have to include the public static void main(String[] args). So lets being with our basic program structure and begin building our Bank class

class Bank
{
    private String bank_name;   // Name of the Bank.
    private Scanner input;
   
    // Constructors
    Bank()  {}
    
    // Overloaded
    Bank(String b_name)
    {
        // Name of Bank is set in constructor  //
        bank_name = b_name;
    }

    int processClients() 
    {
        // We will do our main program flow in here //
    }

    // Main Method
    public static void main(String[] args)
    {
           Bank myBank = new Bank("My Bank Name");
           System.exit ( myBank.processClients() );
    }

}


So i have decided to run the bank from a function int processClients() you may notice it returns an int, this is a habbit i have been getting into as i do most coding on linux systems. The reason i return an int is because the exit status of the program relies on the way this function operates (mainly). Hence i use System.exit( myBank.processClients() ); , essentially this means that if the function runs correctly the program termintates with status System.exit(0); if for some reason there is an errror it will exit with another value for instance System.exit( -1 );

Anyway seem as though the int processClients() is the function for the bank lets begin building it.

Firslty we need to have a way of storing Accounts - so how about an Array ? - for this example we will just create and array of Accounts 32 in total. We will initalise them all to null, by doing this we will be able to terminate loops and input easily later on down the track. Note we are using a fixed size in this case which is the only reason why i have not used methods in determining the Array length.
Account[] pAccounts = new Account[32];

int counter = 0;
while( counter < 32)
{
      pAccounts[counter] = null;
      counter++;
}



Now the way this bank works in passing information to constructors we will need to use a range of tmp (or temporary) variables, also our Scanner which was declared as a private variable in the class needs to be instantiated.

// Some variables for temporarily storing           //
// account credentials in before setting up account //
String tmp_name_f, tmp_name_l;
double tmp_bal;
long tmp_num;

// initalise scanner here to begin gathering user input //
input = new Scanner(System.in);




Now we move into a for loop which is where we being to add our accounts and their related information such as client data, balance, account numbers etc...

System.out.println("Begin Adding Accounts\n==========================================");

for( int i = 0; i < pAccounts.length; i++)
{
            System.out.println("Account Holders First Name :: ");
            tmp_name_f = input.next();
            System.out.println("Account Holders Last Name :: ");
            tmp_name_l = input.next();

            System.out.println("BSB - AccountNumber :: ");
            tmp_num = input.nextLong();
            System.out.println("Opening Balance :: ");
            tmp_bal = input.nextDouble();

            // Store Information in Account Object Array by //
            // initialising accounts as we precede          //
            pAccounts[i] = new Account(new Client( tmp_name_f, tmp_name_l  ), tmp_bal, tmp_num);

            // Check if user wishes to add another account, if "N" //
            // is entered, we break out of account creation loop   //
            System.out.println("Add Another Account ? (Y / N) :: ");
            if(input.next().equals("N"))
                break;
}


Notice we are asked if we wish to input another account, if we choose no we cease the loop and move on to the next section of the program. I would like to draw attention to pAccounts[i] = new Account(new Client( tmp_name_f, tmp_name_l ), tmp_bal, tmp_num); which you may have noticed is in the above code. You may notice we are creating a Client in the function call. The reason for this is because we do not wish the Bank class to have direct access or store any temporary Client objects, hence we send it straight to Account class by initialising it in the function call. using new Client(tmp_name_f, tmp_name_l); - check the client constructor and you will see that we are passing first and last names here.


Now i am about to dump a large chunk of code and i will do my best to run you through it, basically we need to add a few boolean variables to our class variables as we will use them to negate program flow. Basically the following section of code works on the basis that we have instantiated accounts in the previous section, this allows us to select accounts by printing names and indexes, asking the user for an input and once an account is selected it then allows users to perform a number of functions on the account. The Comments for this section will be in the code.

while (bContinue)
{
            int acc;    // account index to access.

            System.out.println("\nSelect Account - Index\n==========================================");

            for ( int k = 0; k < pAccounts.length; k++)
            {
                // earlier we initialised accounts to null                                     //
                // this check is just to ensure the account is valid and has been instantiated //
                if(pAccounts[k] != null)
                System.out.println(k + " ) " + pAccounts[k].get_name() + "\nAccount Number : " + pAccounts[k].get_account_number() );
            }
            acc = input.nextInt();

            // This Boolean indicates the user wishes to continue on with the same account //
            while (bAcc)
            {
                // This could be done in a switch statement, however i prefer if's. //
                // basically, we select which member function of Account to call    //
                // for the account designated in the code above, each selection     //
                // either fetches or changes values of a specific account denoted   //
                // by index.                                                        //

                // This section will allow users to perform functions
                System.out.println("\nChoose Function\n1 ) Deposit\n2 ) Withdraw\n3 ) Balance Enquiry\n4 ) Show Contact Detail");
                int sel = input.nextInt();
                if ( sel == 1)
                {
                    System.out.println("Enter Amount to Deposit = $ ");
                    pAccounts[acc].deposit_funds(input.nextDouble() );
                }
                else if ( sel == 2)
                {
                    System.out.println("Enter Amount To Withdraw = $ ");
                    if( pAccounts[acc].withdraw_funds(input.nextDouble() ) == -1)
                    {
                        System.out.println("Insufficient Funds");
                    }
                    else
                        System.out.println("Take your Funds");
                }
                else if ( sel == 3)
                {
                    System.out.println("Balance = $ " + String.format("%.2f", pAccounts[acc].get_balance()) );
                }
                else if (sel == 4)
                {
                    System.out.println("Current Contact Number : " + pAccounts[acc].getClient().getPhoneNumber() );

                    /*
                     * You could in here also have an option to change contact details
                     * a call such as
                     * pAccounts[acc].getClient().set_or_change_phoneContact( 55202020 )
                     * would do this
                     */
                }
                else
                    System.out.println("Invalid Selection");

                // Check if user would like to change accounts or continue with current account //
                System.out.println("Continue With This Account\n1 ) Yes\n2 ) No");
                if( input.nextInt() == 1)
                        bAcc = true;
                else bAcc = false;
            }
            bAcc = true;

            // Check if to continue on with banking system.
            System.out.println("Would You Like To Continue\n1 ) Yes\n2 ) No");
            if (input.nextInt() == 1) bContinue = true;
            else
                return 0;   // we return early and essentially exit program //

}


So thats basically our complete code - here is the complete class for Bank

import java.util.*;

public class Bank
{
    private String bank_name;   // Name of the Bank.
    private Scanner input;      // private scanner to retrieve
                                // user input.

    // Some Booleans to control program flow //
    private boolean bContinue = true;
    private boolean bAcc = true;

    // constructors
    Bank()  {}

    Bank(String b_name)
    {
        // Name of Bank is set in constructor  //
        bank_name = b_name;
    }

    int processClients()
    {
        System.out.println("\t" + bank_name.toUpperCase());
        System.out.println("==========================================");

        // System has a possible 32 accounts to be used //
        Account[] pAccounts = new Account[32];

        // In the following loop we initialise the accounts all to null //
        // which makes it easier to find a terminating account when     //
        // looping later on in the code - as we can check if an account //
        // is null and subsequently know that no accounts in the array  //
        // after such point have been initialised.                      //
        int counter = 0;
        while( counter < 32)
        {
            pAccounts[counter] = null;
            counter++;
        }


        // Some variables for temporarily storing           //
        // account credentials in before setting up account //
        String tmp_name_f, tmp_name_l;
        double tmp_bal;
        long tmp_num;

        // initalise scanner here to begin gathering user input //
        input = new Scanner(System.in);

        // Below we will being adding accounts to the database / array //
        // this loop continues till a terminating condition is met.    //

        System.out.println("Begin Adding Accounts\n==========================================");

        for( int i = 0; i < pAccounts.length; i++)
        {
            System.out.println("Account Holders First Name :: ");
            tmp_name_f = input.next();
            System.out.println("Account Holders Last Name :: ");
            tmp_name_l = input.next();

            System.out.println("BSB - AccountNumber :: ");
            tmp_num = input.nextLong();
            System.out.println("Opening Balance :: ");
            tmp_bal = input.nextDouble();

            // Store Information in Account Object Array by //
            // initialising accounts as we precede          //
            pAccounts[i] = new Account(new Client( tmp_name_f, tmp_name_l  ), tmp_bal, tmp_num);

            // Check if user wishes to add another account, if "N" //
            // is entered, we break out of account creation loop   //
            System.out.println("Add Another Account ? (Y / N) :: ");
            if(input.next().equals("N"))
                break;
        }

        // The boolean here, indicates user wishes to continue utilising the Banking System //
        while (bContinue)
        {
            int acc;    // account index to access.

            System.out.println("\nSelect Account - Index\n==========================================");

            for ( int k = 0; k < pAccounts.length; k++)
            {
                // earlier we initialised accounts to null                                     //
                // this check is just to ensure the account is valid and has been instantiated //
                if(pAccounts[k] != null)
                System.out.println(k + " ) " + pAccounts[k].get_name() + "\nAccount Number : " + pAccounts[k].get_account_number() );
            }
            acc = input.nextInt();

            // This Boolean indicates the user wishes to continue on with the same account //
            while (bAcc)
            {
                // This could be done in a switch statement, however i prefer if's. //
                // basically, we select which member function of Account to call    //
                // for the account designated in the code above, each selection     //
                // either fetches or changes values of a specific account denoted   //
                // by index.                                                        //

                System.out.println("\nChoose Function\n1 ) Deposit\n2 ) Withdraw\n3 ) Balance Enquiry\n4 ) Change Contact Details");
                int sel = input.nextInt();
                if ( sel == 1)
                {
                    System.out.println("Enter Amount to Deposit = $ ");
                    pAccounts[acc].deposit_funds(input.nextDouble() );
                }
                else if ( sel == 2)
                {
                    System.out.println("Enter Amount To Withdraw = $ ");
                    if( pAccounts[acc].withdraw_funds(input.nextDouble() ) == -1)
                    {
                        System.out.println("Insufficient Funds");
                    }
                    else
                        System.out.println("Take your Funds");
                }
                else if ( sel == 3)
                {
                    System.out.println("Balance = $ " + String.format("%.2f", pAccounts[acc].get_balance()) );
                }
                else if (sel == 4)
                {
                    System.out.println("Current Contact Number : " + pAccounts[acc].getClient().getPhoneNumber() );

                    /*
                     * You could in here also have an option to change contact details
                     * a call such as
                     * pAccounts[acc].getClient().set_or_change_phoneContact( 55202020 )
                     * would do this
                     */
                }
                else
                    System.out.println("Invalid Selection");

                // Check if user would like to change accounts or continue with current account //
                System.out.println("Continue With This Account\n1 ) Yes\n2 ) No");
                if( input.nextInt() == 1)
                        bAcc = true;
                else bAcc = false;
            }
            bAcc = true;

            // Check if to continue on with banking system.
            System.out.println("Would You Like To Continue\n1 ) Yes\n2 ) No");
            if (input.nextInt() == 1) bContinue = true;
            else
                return 0;   // we return early and essentially exit program //

        }

        return 0;
    }
    public static void main(String[] args)
    {
        Bank myBank = new Bank("National Australia Bank");
        System.exit( myBank.processClients() );
    }
}



Asside
There were a few if's i spoke about that we might like to do, one very simple improvement or change would be the incurring of a withdrawal fee when an account holder chooses to make a withdrawal. This is suprising simple to implement, we simply would look into our withdraw function in Account class and modify it with a charge... For example if we had a $2 fee we could do something as simple as

public int withdraw_funds( double p_amount)
 {
        // check if enough funds
        if ( (p_amount + 2) > balance )
            return -1;
        else
            balance -= ( p_amount + 2 );
        return 0;
 }



Thats just one very simple example of how we can easily improve / change classes later on if we have to implement some other functionalities. Hence the reason why if the function contained System.out statements rather than relying on paramaters being passed to the function we would have a lot more work to do.


This is my first tutorial, so i am hoping this has been helpful to people on dreamincode.

Thanks for reading
bbq

Is This A Good Question/Topic? 2
  • +

Page 1 of 1