![](../../../javaimages/course-previous.gif)
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 function is the special
one that's provided to allow us to make a string value of the object.
As you notice, it's called toString. That name is fixed; you have
to use that name. It cannot take any parameters and it must return
a String value. But that's part of the convention of overriding what's
provided in Java's Object class.
As a side note, remember up at
the top, we just said 'public class BankAccount'. We didn't specify
any class that we inherited from. Just remember that all Java classes
inherit from Java's Object if it's not specified. And that's Object,
with a capital 'O.'
So, let's look in a little deeper
at the toString method. In there is a return super.toString.
The word 'super' is a keyword in the Java language, and it says that the
super class' toString is going to be invoked. Well, what is BankAccount's
superclass? It's Object, and so it's going to invoke Object's toString
method and then concatenate with it (notice the plus signs) a string that
has the id and another string that has the balance in it. When we
get done, we'll have some indicator specifying the object itself, followed
by these two values. If you remember when we executed it, you saw
the word BankAccount@ and a hexadecimal number. Object actually returns
the class name, @, and then the address of the object. That's Object's
default behavior for its toString. You don�t have to use super.toString
if you don't want to; it's there if you need it."
![](../../../javaimages/course-previous.gif)
|