Java Reference
In-Depth Information
Display 13.9 Class with an Inner Class (part 2 of 2)
19
return (dollars + "." + cents);
20
else
21
return (dollars + ".0" + cents);
22
}
23
public void addIn(Money secondAmount)
24
{
25
abortOnNull(secondAmount);
26
int newCents = (cents + secondAmount.cents)%100;
27
long carry = (cents + secondAmount.cents)/100;
28
cents = newCents;
29
dollars = dollars + secondAmount.dollars + carry;
30
}
31
private void abortOnNull(Object o)
32
{
33
if (o == null )
34
{
35
System.out.println("Unexpected null argument.");
36
System.exit(0);
37
}
The definition of the inner class ends here, but the definition
of the outer class continues in Part 2 of this display.
38
}
39
}
40
private Money balance;
To invoke a nonstatic method of the
inner class outside of the inner class,
you need to create an object of the inner
class.
41
public BankAccount()
42
{
43
balance = new Money("0.00");
44
}
This invocation of the inner class
method getAmount() would be
allowed even if the method
getAmount() were marked as
private .
45
public String getBalance()
46
{
47
return balance.getAmount();
48
}
49
public void makeDeposit(String depositAmount)
50
{
51
balance.addIn( new Money(depositAmount));
52
}
53
public void closeAccount()
Notice that the outer class has access
to the private instance variables of the
inner class.
54
{
55
balance.dollars = 0;
56
balance.cents = 0;
57
}
This class would normally have more methods, but we have only
included the methods we need to illustrate the points covered here.
58
}
 
Search WWH ::




Custom Search