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:

"The next two things in this file are static information. Static means these are class variables and class methods. This says that for all the instances of bank accounts, whether it is Bank Account 122 or 135 or 822, for these objects there's only going to be one piece of information and it's shared among all the bank account objects that we create. In this case, we have a nextId_ field, which says that the shared or common source for bank account identifiers is going to start initially at one hundred. Notice the format of this statement: we have the accessor, followed by static, followed by the type, then the variable name equals an initialization value. That's a typical way of handling it. Realize again that when the class is loaded, this variable is going to be initialized to one hundred. That's how we do things in Java, as compared to other languages such as C++, where we have a separate header file and source code file. Here everything's in one file, so we combine the two constructs together, both the declaration and initialization. Immediately following is our newId method, which is a class method that references the class variable. And its job is to return nextId_ and increment it. This says that each time we construct a class, it's going to come out with a number that starts at one hundred, goes to 101 and continues thereon."