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 first thing it did was define two bank accounts: BankAccount 'a' and
BankAccount 'b' . And it created new objects for them. It went out and allocated
in the heap two bank account objects, one of which took a single argument
$15.25 and another which took no arguments. Now if you remember the code,
the first line 'a' specifies one argument and invokes the second constructor we
talked about. The second entry 'b' will actually invoke the first constructor, which
in turn by using this(0.0) will invoke the second constructor, so there's a cascade
of invocations here. The result is that we have two bank account objects, 'a' and
'b'. Also note that 'a' and 'b' are not objects themselves but variables that
reference objects. Remember this. It is really hard to keep track of. Java
always says if you have an object type, meaning a bank account in this case,
that 'a' and 'b' are not solid objects on the stack as in C++, but are references to
them. Again, you can think of the fact that 'a' and 'b' are similar to pointers, even
though you don�t specify the asterisks (denoting a pointer) as you would in C and
C++."