Java Reference
In-Depth Information
describes classes and their properties. Then invoke the getName method to get
the name of the class:
public String toString()
{
return getClass().getName() + Ð[balance=Ñ
+ balance + Ð]Ñ;
}
Then the toString method prints the correct class name when you apply it to
a subclass, say a SavingsAccount .
467
468
SavingsAccount momsSavings = . . . ;
System.out.println(momsSavings);
// Prints ÐSavingsAccount[balance=10000]Ñ
Of course, in the subclass, you should override toString and add the values
of the subclass instance fields. Note that you must call super.toString to
get the superclass field valuesȌthe subclass can't access them directly.
public class SavingsAccount extends BankAccount
{
public String toString()
{
return super.toString() +
Ð[interestRate=Ñ + interestRate + Ð]Ñ;
}
}
Now a savings account is converted to a string such as
SavingsAccount[balance=10000][interestRate=5] . The
brackets show which fields belong to the superclass.
10.8.2 Overriding the equals Method
The equals method is called whenever you want to compare whether two objects
have the same contents:
if (coin1.equals(coin2)) . . .
// Contents are the sameȌsee Figure 9
Search WWH ::




Custom Search