Java Reference
In-Depth Information
5.
Create a new class
SavingsAccount
that implements the
Accountable
interface. You can
add interfaces in the middle of the New Java Class window, or you can type
implements
Accountable
yourself after the class is created. If you add it from the window, the necessary meth-
ods will automatically be created for you to implement.
6.
The
SavingsAccount
class should have two instance variables: name and amount. Follow the prin-
ciple of information hiding. Use the
isValid
methods to check if a String is numeric and if it can
be represented as a
BigDecimal
. Before making a deposit or withdrawal, use the
isValid
methods
to check if the transaction is valid. Override the
toString()
method to print information about
your accounts. Your
SavingsAccount
class may look like this:
import java.math.BigDecimal;
public class SavingsAccount implements Accountable {
private String name;
private BigDecimal amount;
public SavingsAccount(String name, String amount) throws IllegalAccount {
if (isValidDeposit(amount)) {
this.setName(name);
this.setAmount(new BigDecimal(amount));
} else {
throw new IllegalAccount();
}
}
@Override
public boolean isValidDeposit(String deposit) {
BigDecimal temp;
try {
temp = new BigDecimal(deposit);
} catch (Exception e) {
return false;
}
return temp.compareTo(BigDecimal.ZERO) > 0;
}
@Override
public void deposit(String deposit) throws IllegalDeposit {
if (isValidDeposit(deposit)) {
this.setAmount(this.getAmount().add(new BigDecimal(deposit)));
} else {
throw new IllegalDeposit();
}
}
@Override
public boolean isValidWithdrawal(String withdrawal) {
BigDecimal temp;
try {
temp = new BigDecimal(withdrawal);
} catch (Exception e) {
return false;
Search WWH ::
Custom Search