package exer2;
public class Account {
private int id;//账号
private double balance;//余额
private double annualInterestRate;//构造器
public Account(int id,double balance,double annualInterstRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterstRate;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMonthlyInsert() {
return annualInterestRate/12;
}
public void withdraw(double amount) { //取款
if(balance >= amount) {
balance -= amount;
return;
}
System.out.println("余额不足");
}
public void deposit(double amount) { //存款
if(amount > 0) {
balance += amount;
}
}
}
package exer2;
public class AccountTest {
public static void main(String[] args) {
Account a = new Account(1122,20000,0.045);
a.withdraw(30000);
System.out.println("您的账户余额为:"+a.getBalance());
a.withdraw(2500);
System.out.println("您的账户余额为:"+a.getBalance());
a.deposit(3000);
System.out.println("您的账户余额为:"+a.getBalance());
System.out.println("月利率为:"+(a.getMonthlyInsert()*100)+"%");
}
}
package exer2;
public class CheckAccount extends Account {
private double overdraft; // 可透支限额
public CheckAccount(int id, double balance, double annualInterstRate, double overdraft) {
super(id, balance, annualInterstRate);
this.overdraft = overdraft;
}
@Override
public void withdraw(double amount) {
if(getBalance() >= amount) { //余额足够消费
//方法一
// setBalance(getBalance() - amount);
//方法二
super.withdraw(amount);
}else if(overdraft >= (amount - getBalance())){ //透支额度 + 余额足够消费
overdraft -= (amount - getBalance());
// setBalance(0);
//或
super.withdraw(getBalance());
}
else {
System.out.println("超过可透支限额!");
}
}
public double getOverdraft() {
return overdraft;
}
public void setOverdraft(double overdraft) {
this.overdraft = overdraft;
}
}
package exer2;
public class CheckAccountTest {
public static void main(String[] args) {
CheckAccount acct = new CheckAccount(1122, 20000, 0.045, 5000);
acct.withdraw(5000);
System.out.println("您的账户余额为:"+acct.getBalance());
System.out.println("您的可透支额度为:"+acct.getOverdraft());
acct.withdraw(18000);
System.out.println("您的账户余额为:"+acct.getBalance());
System.out.println("您的可透支额度为:"+acct.getOverdraft());
acct.withdraw(3000);
System.out.println("您的账户余额为:"+acct.getBalance());
System.out.println("您的可透支额度为:"+acct.getOverdraft());
}
}