账号类 :
package day08_06;
public class Account {
private int id;
private double balance;
private double annualInterstRate;
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 getAnnualInterstRate() {
return annualInterstRate;
}
public void setAnnualInterstRate(double annualInterstRate) {
this.annualInterstRate = annualInterstRate;
}
public Account(int id, double balance, double annualInterstRate) {
super();
this.id = id;
this.balance = balance;
this.annualInterstRate = annualInterstRate;
}
public Account() {
super();
}
// 当前月利率
public double getMonthlyInterest(){
return this.annualInterstRate/12;
}
// 消费
public void withdraw(double amount){
if(this.balance>=amount){
this.balance-=amount;
}else{
System.out.println("当前余额不足");
}
}
// 存钱
public void deposit(double amount){
this.balance+=amount;
}
}
子类 : 重写父类方法 Override
package day08_06;
public class CheckAccount extends Account{
private double overdraft;
@Override
public void withdraw(double amount) {
if(amount<super.getBalance()){
super.withdraw(amount);
}else if(amount > super.getBalance()){
if((amount-super.getBalance()) > overdraft ){
System.out.println("超过可透支额度的限额!");
}else{
this.overdraft-=(amount-super.getBalance());
super.setBalance(0);
}
}
}
public double getOverdraft() {
return overdraft;
}
public void setOverdraft(double overdraft) {
this.overdraft = overdraft;
}
}
测试父类的方法
package day08_06;
public class TestAccount {
public static void main(String[] args) {
Account acc = new Account(1000,20000,0.045);
acc.deposit(30000);
acc.withdraw(2000);
System.out.println(acc.getBalance());
}
}
测试重写后 子类的方法
package day08_06;
public class TestCheckAccount {
public static void main(String[] args) {
CheckAccount ca=new CheckAccount();
ca.setBalance(20000);
ca.setAnnualInterstRate(0.045);
ca.setId(1122);
ca.setOverdraft(5000);
ca.withdraw(5000);
System.out.println(ca.getBalance()+":-可透支额度"+ca.getOverdraft());
ca.withdraw(18000);
System.out.println(ca.getBalance()+":-可透支额度"+ca.getOverdraft());
ca.withdraw(3000);
System.out.println(ca.getBalance()+":-可透支额度"+ca.getOverdraft());
}
}