Java基础语法51-继承和super的练习
本实验来自于尚硅谷java基础班,如果侵权请告知。
package com.atguigu.exer1;
public 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 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 double getMonthlyInterest(){
return annualInterestRate/12;
}
//取钱
public void withdraw (double amount){
if(balance >= amount){
balance -= amount;
}
}
//存钱
public void deposit (double amount){
if(amount > 0){
balance += amount;
}
}
}
package com.atguigu.exer1;
public class AccountTest {
public static void main(String[] args) {
Account account = new Account(1122, 20000, 0.045);
account.withdraw(30000);
System.out.println("您的账户余额为:" + account.getBalance());
account.withdraw(2500);
System.out.println("您的账户余额为:" + account.getBalance());
account.deposit(3000);
System.out.println("您的账户余额为:" + account.getBalance());
System.out.println("月利率为:" + account.getMonthlyInterest()*100+'%');
}
}
package com.atguigu.exer1;
public class CheckAccount extends Account {
private double overdraft;//可透支限额
public double getOverdraft() {
return overdraft;
}
public void setOverdraft(double overdraft) {
this.overdraft = 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 (getBalance() >= amount) {//余额足够的情况
// setBalance(getBalance() - amount);
super.withdraw(amount);
} else if (overdraft >= amount - getBalance()) {//透支额度+余额足够消费
overdraft -= (amount - getBalance());
setBalance(0);
}else{
System.out.println("超过可透支限额!");
}
}
}
package com.atguigu.exer1;
public class CheckAccountTest {
public static void main(String[] args) {
CheckAccount checkAccount =new CheckAccount(1122, 20000, 0.045, 5000);
checkAccount.withdraw(5000);
System.out.println("您的账户余额为:" + checkAccount.getBalance());
System.out.println("您的透支额度为:"+checkAccount.getOverdraft());
checkAccount.withdraw(18000);
System.out.println("您的账户余额为:" + checkAccount.getBalance());
System.out.println("您的透支额度为:"+checkAccount.getOverdraft());
checkAccount.withdraw(3000);
System.out.println("您的账户余额为:" + checkAccount.getBalance());
System.out.println("您的透支额度为:"+checkAccount.getOverdraft());
}
}