Java Reference
In-Depth Information
int balance;
SavingsAccount deposit(int amount)
{
balance += amount;
return this;
}
SavingsAccount printBalance()
{
System.out.println(balance);
return this;
}
public static void main(String[] args)
{
new SavingsAccount().deposit(1000).printBalance();
}
}
Listing2-10
showsthatyoumustspecifytheclass'snameastheinstancemethod'sre-
turntype.Eachof
deposit()
and
printBalance()
mustspecify
SavingsAc-
count
asthereturntype.Also,youmustspecify
return this;
(returncurrentob-
ject's reference) as the last statement—I discuss the return statement later.
For example,
new SavingsAc-
count().deposit(1000).printBalance();
creates a
SavingsAccount
object, uses the returned
SavingsAccount
reference to invoke
SavingsAc-
count
's
deposit()
instancemethod,toaddonethousanddollarstothesavingsac-
count (I'm ignoring cents for convenience), and finally uses
deposit()
's returned
SavingsAccount
reference(whichisthesame
SavingsAccount
instance)toin-
voke
SavingsAccount
's
printBalance()
instancemethodtooutputtheaccount
balance.
Declaring and Invoking Class Methods
In many situations, instance methods are all that you need. However, you might en-
counter a situation where you need to describe a behavior that is independent of any
object.
Forexample,supposeyouwouldliketointroducea
utility class
(aclassconsistingof
static
[class] methods) whose methods perform various kinds of conversions (such