Java Bank Account


public class BankAccount {

    public BankAccount () { this(0.0) ; } 
   
    public BankAccount( double initBal )
       { balance_=initBal; id_=newID(); }

    public double balance() { return balance_; }
    public int   id()       { return id_; }

    public void withdraw(double amt) { balance_ -=amt; }
    public void  deposit(double amt) { balance_ +=amt; }

    public String toString()    
       { return super.toString() + "(id:" + id_ + ", bal:" + balance_ + ")" ; }

    // Instance variables
    private double balance_;
    private int id_;

    // Class variable and class method
    public static int nextID_=100;
    private static int newID() { return nextID_++; }

    // Another "special" class method
    public static void main(String args[]) {

    BankAccount a=new BankAccount(15.25);
    BankAccount b=new BankAccount();

    System.out.println("a=" + a.toString() );
    System.out.println("b=" + b.toString() );

    a.withdraw(5.50);
    b.deposit(125.99);

    System.out.println("a=" + a);
    System.out.println("b=" + b);

    System.exit(0);     
    } // no semi-colon
}

Detailed Description:

"Finally, we'll wrap up the program with two more outputs very much like what we had done before. In this case, we're going to print out 'a' and 'b'. But notice the difference here. We're just saying '"a="+a'. The convention is that when we need to convert something to string, the toString method is implicitly invoked. So we don't even have to specify toString. That simplifies the codes, and makes it a little easier to read. We end the program by a system.exit with a zero, which represents the return code. System is that class again, the general System class we'll be using throughout the course. Exit says stop the Java virtual machine right now, and that ends the program.

So our main routine creates a couple of accounts, does some work with printing them out, does some withdrawals and deposits, and finally wraps up by printing them out again and shutting down. That's all the capability that it's going to provide."