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:

"Our first thing is our BankAccount class. And we have a public class, which says that it's exported outside our class library. The name of class is BankAccount with a capital B and a capital A. The class begins with an open brace and ends with a closed brace without a semicolon -- down at the end. At the beginning, we have what's called constructors, which are public methods. They are a special type of method in that they have the same name as the class and they have no return type. If you notice, there is a little twist here for those with a C++ background. In the first constructor, we're using 'this'. The word 'this' is a keyword and it represents the current object. In this case, we have 'this' followed by 0.0 in parentheses. We're taking one constructor and invoking another constructor. Realize that this particular constructor takes zero arguments and invokes the one argument constructor passing it a default value. Java does not have default parameters like C++, so this is a way one can do it. The second constructor is the constructor that's going to be invoked using that first constructor. It takes a single argument, which happens to be a double, which is the initial balance, and the body of the function sets balance_ equal to that initial balance. It also does one other thing. It sets the id_ field, and we'll deal with that in just a minute."