Hey Folks,

This is all about the post

What: Object Interaction

Language: Java

Example Illustrated: CheckingBankAccount

Functionalities : Create, Credit, Debit, Display Bank accounts

DataStructure used : Hashtable ( To store and lookup accounts)

Constraints :    Every debit made from an a/c with  less than $100 will be charged $10 fee

Every debit made from an a/c with less than $0 balance will be charged $30 overdraft fee

How many classes : 3 (CheckingAccount.java, AccountTable.java, Tester.java)

Points to note :

CheckingAccount.java and AccountTable.java are defined in a PACKAGE checkingaccount

Data members of  CheckingAccount.java don’t have any access-modifier (default modifier) . So it is visible for all classes in its own package . In other  words, AccountTable.java can access it directly without using any get methods.

But, main class (Tester.java) is the one the user directly interacts with. User shouldn’t have access to the datamembers of bank  account. In real world, a customer can credit or debit or view his own account details and not any body else. So giving access to  the hashtable of accounts (AccountTable.java) is a very poor design and SHOULD BE AVOIDED.

Its for this reason,  CheckingAccount and  the data structure to hold it (AccounTable ) are in one package and they can access directly the datamembers of each other whereas to keep the user away, Tester.java is out of the checkingaccount package.

This way a user can  interact with account classes only via accessors and mutators (get and set methods) and not directly with the data members of  those classes.  Now it makes sense why Tester was outside the package. If not, it can access the datamembers of other two classes directly.

As an example, thats why  to access  balance a datamember of CheckingAccount.java    Tester.java uses account.getBalance() [an accessor – as datamember ‘balance’ cant be accessed directly outside the package ] and  AccountTable.java uses account.balance as it is in the same package as CheckingAccount.java. The respective  lines is made bold  and Italicized in the code as well. Check it out below

Compilation :

1. Say you copy paste the Tester.java to a folder Bank

2. Create a folder checkingaccount inside Bank folder

3. Copy paste the remaining two java files to checkingaccount folder

Now, if u r under Linux OS, you may have something like

usr-name:~bank/ ls

Tester.java                     checkingaccount

usr-name:~bank/cd checkingaccount

usr-name:~bank/ checkingaccount/ ls

CheckingAccount.java              AccountTable.java

Now give                     javac *.java (This creates class files for the above two java files)

Now  cd .. and come to the parent directory (bank)

Now give                   javac   Tester.java to create Tester.class

Now to execute the program give                  java  Tester

So here is the code!

//Tester.java

/**
 *
 * @author poochedi
 */
import java.util.*;
import checkingaccount.*;

public class Tester {

      public static void main(String[] args) {

          System.out.println("Enter Your option (1-4) to continue and 5 to exit");
          System.out.println("1.CREATE ACCOUNT 2.CREDIT 3.DEBIT 4.DISPLAY 5.EXIT" );

          //create an object for hashtable
          AccountTable table = new AccountTable();

          Scanner scanObject = new Scanner(System.in);
          Scanner scanDetails;
          while( scanObject.hasNextLine() ) {

               int option = scanObject.nextInt();
               if(option > 5)
                System.out.println("Enter a number from 1-5");

               if(option == 1) {

                   //create an account
                   scanDetails = new Scanner(System.in);
                   System.out.println("Enter the following details");

                   System.out.println("Name");
                   String name = scanDetails.next();

                   System.out.println("A/c Number");
                   String acNumber = scanDetails.next();

                   CheckingAccount account = new CheckingAccount(name, acNumber);

                   //add the account to hash table
                   table.addAccount(account);
                   System.out.println("Account created successfully");
               }

               if(option == 2) {

                  //Credit to account
                  scanDetails = new Scanner(System.in);
                  System.out.println("Enter the name of the a/c holder");
                  String name = scanDetails.next();

                  CheckingAccount account = table.searchAccount(name);

                  if(account != null)
                  {
                    System.out.println("Enter the amount to be credited ");
                    double amount = Double.parseDouble(scanDetails.next());
                    account.credit(name, amount);
                    double newBalance = account.getBalance();
                    table.updateBalance(name,newBalance);
                  }
                  else
                    System.out.println("No such account found");
               }

               if(option == 3) {

                  //Debit from account
                  scanDetails = new Scanner(System.in);
                  System.out.println("Enter the name of the a/c holder");
                  String name = scanDetails.next();          

                  CheckingAccount account = table.searchAccount(name);
                  if(account != null) {

                    System.out.println("Enter the amount to be debited ");
                    double amount = Double.parseDouble(scanDetails.next());
                    account.debit(amount);
                    //put into table the updated details
                    double newBalance = account.getBalance();
                    table.updateBalance(name,newBalance);

                  }
                  else
                    System.out.println("No such account found");
               }

               if(option == 4) {

                 //display account details
                 scanDetails = new Scanner(System.in);
                 System.out.println("Enter the name of the a/c holder");
                 table.displayAccount();
               }

               if(option == 5) {

                  System.out.println("Thanks for using our service");
                  System.exit(0);
               }

               System.out.println("Enter Your option (1-4) to continue and 5 to exit");
               System.out.println("1.CREATE ACCOUNT 2.CREDIT 3.DEBIT 4.DISPLAY 5.EXIT");
               scanObject = new Scanner(System.in);
          }
    }

}
===================================================================================================================
//AccountTable.java
package checkingaccount;

/**
 *
 * @author poochedi
 */
import java.util.*;

public class AccountTable {

       //data member
      //DEFAULT access modifier
      //ACCESSIBLE ONLY WITHING THE PACKAGE
      Hashtable <String, CheckingAccount> table;

      //==========================================================================================================

      public AccountTable() {

          table = new Hashtable();
      }

      //==========================================================================================================

      public void addAccount(CheckingAccount account) {

          String key = account.accountHolder;
          table.put(key, account);
      }

//==========================================================================================================

      public CheckingAccount searchAccount(String name) {

              if(table.containsKey(name))
                    return table.get(name);
              return null;
      }

//==========================================================================================================

      public void displayAccount() {

              Enumeration enumObj = table.keys();
              while(enumObj.hasMoreElements()) {

                    String acNumber = (String) enumObj.nextElement();
                    CheckingAccount acc = table.get(acNumber);
                    System.out.print(acc.accountHolder + " ");
                    System.out.print(acc.accountNumber + " ");
                    System.out.print(acc.overDraftCount + " ");
                    System.out.println(acc.balance + " ");
              }
      }

//==========================================================================================================

      public void updateBalance(String name, double balance) {

            if(table.containsKey(name)) {

                  CheckingAccount acc = table.get(name);
                  acc.balance = balance;
                  table.put(name, acc);
            }
      }
}
===================================================================================================================
//CheckingAccount.java
package checkingaccount;

/**
 *
 * @author poochedi
 */

public class CheckingAccount {

        //data members -- DEFAULT access modifier
        //So ACCESSIBLE ONLY WITHIN THE PACKAGE
         String accountHolder;
         String accountNumber;
         double balance;
         int overDraftCount;

        //default constructor
        public CheckingAccount() {

            accountHolder = " ";
            accountNumber = "0000000-000";
            balance = 0.00;
            overDraftCount = 0;
        }

        //parameterized constructor
        public CheckingAccount(String acOwner, String acNumber) {

            accountHolder = acOwner;
            accountNumber = acNumber;
            balance = 0.00;
            overDraftCount = 0;

        }

//==========================================================================================================

        //mutators - set method - Process credit
        //add amount to balance
        public void credit(String name, double amountCredited) {

                //Search the account
                double totalOverDraftCharge = this.overDraftCount * 30;
                this.balance = this.balance + amountCredited - totalOverDraftCharge;
        }

//==========================================================================================================

        //mutators - set method - Process debit
        //deduct amount from balance
        public void debit(double amountToDeduct) {

                 double charge = 0.00;
              //if balance less than $100 deduct $10 for every check processed

                      if(this.balance < 100)
                          charge = 10.00;
                      this.balance = this.balance - amountToDeduct - charge;
                      if(this.balance < 0)
                          this.overDraftCount++;
        }

//==========================================================================================================

        //accessors - get methods - get the balance
        public double getBalance() {

                 //Search the account
                  return this.balance;
        }

}
Advertisements