继承javabank帐户(java)
我在一个遗产银行账户上工作,该账户有5个等级。在其中一个类别(InterestFreeDeposit)中,应使用至少10美元创建帐户。我应该如何编写这部分的代码? 以下是我迄今为止所做的工作:
超类:
import java.util.Scanner;
import java.io.FileReader;
public class Account {
private String owner;
private double balance;
private int accountNumber;
private double interestRate;
public Account( String owner,double balance, int accountNumber , double interestRate){
this.balance=balance;
this.owner=owner;
this.accountNumber=accountNumber;
this.interestRate=interestRate;
}
public void deposit(double amount) {
if(amount>0) {
this.balance+=amount;
}
}
public void withdraw(double amount) {
if(amount>0 && balance>=amount) {
this.balance-=amount;
}
}
public double getBalance() {
return balance;
}
public void setBalance(double amount) {
this.balance = amount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public double getInterestRate() {
return interestRate;
}
public double setInterestRate(double interestRate) {
//System.out.println("Enter the period(month):");
return this.balance +=balance * interestRate/100;
}
子类(InterestFrreClass):
public class InterestFreeDeposit extends Account {
public InterestFreeDeposit(String owner, double balance, int accountNumber, double interestRate) {
super(owner, balance, accountNumber, interestRate);
// TODO Auto-generated constructor stub
}
public void interest() {
super.setInterestRate(0.0) ;
}
}
# 1 楼答案
设置值时需要添加检查,在本例中,检查发生在
InterestFreeDeposit
的构造函数中。问题是当值低于10
时,您希望如何反应。您可以抛出一个IllegalArgumentException
:这种方法的问题是
IllegalArgumentException
是一个未检查的异常,这意味着如果抛出构造函数,则构造函数的调用方不会被迫处理它# 2 楼答案
您可以在子类构造函数中使用三元运算符来默认为
10.0
最小值:三元运算符可视为内联if。因此,您有以下结构:
在上面的代码片段中,它只是检查所提供的余额是否低于
10.0
。如果是,则将其设置为10,否则将传递: