继承与方法重写
public class Test {
public static void main(String[] args) {
Account account = new Account(1122, 20000, 0.045);
account.withdraw(3000);
account.withdraw(2500);
account.deposit(3000);
System.out.println(account.getMonthlyInterest());
CheckAccount checkAccount = new CheckAccount(1122, 20000, 0.045, 5000);
checkAccount.withdraw(5000);
checkAccount.withdraw(18000);
checkAccount.withdraw(3000);
}
}
class Account {
private int id;
private double balance;
private double annualInterestRate;
public Account (int id, double balance, double annualInterestRate ){
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public double getMonthlyInterest(){
return annualInterestRate/12;
}
public void withdraw (double amount){
if(amount <= 0){
System.out.println("请重新输入!");
return;
}else if(amount > balance){
System.out.println("余额不足");
return;
}
balance -= amount;
System.out.println("成功取出" + amount + " 余额为:" + balance);
}
public void deposit (double amount){
if(amount <= 0){
System.out.println("操作有误,请重试");
}
balance += amount;
System.out.println("存款成功!" + " 余额为:" + balance);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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 class CheckAccount extends Account{
double overdraft;
public CheckAccount(int id, double balance, double annualInterestRate, double overdraft) {
super(id, balance, annualInterestRate);
this.overdraft = overdraft;
}
@Override
public void withdraw(double amount) {
if(amount <= 0){
System.out.println("操作失败!");
return;
}
if(amount <= this.getBalance()){
double b = this.getBalance() - amount;
this.setBalance(b);
System.out.println("成功取出" + amount + " 余额为:" + this.getBalance() + " 可透支额度为:" + overdraft);
}else{
double b2 = amount - this.getBalance();
if(b2 <= overdraft){
this.setBalance(0);
overdraft -= b2;
System.out.println("成功取出" + amount + " 余额为:0 透支了:" + b2 + " 透支额度剩余:" + overdraft);
}else{
System.out.println("超过可透支额度,取款失败!");
}
}
}
}
