0
点赞
收藏
分享

微信扫一扫

Java、账户类Account的子类

爱读书的歌者 2022-03-19 阅读 72
p2plinqc#


package pack1;

import java.util.Date;

public class Account {
    private int id; //账号
    private double balance; //余额
    public static double annualInterestRate;    //年利率
    private Date dateCreated = new Date();  //开户时间

    public Account() {
    }

    /**带指定账号、余额的构造方法*/
    public Account(int id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    /**取款*/
    public boolean withdraw(double amount) {
        if(amount < 0 || amount > balance)
            return false;
        balance -= amount;
        return true;
    }

    /**存款*/
    public boolean deposit(double amount) {
        if (amount < 0) return false;
        balance += amount;
        return true;
    }

    @Override   /**返回账号、余额、开户日期的字符串*/
    public String toString() {
        return "Id: " + id + "\nBalance: " + balance + "\nDate created: " + dateCreated;
    }

    /**返回账号*/
    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 static double getAnnualInterestRate() {
        return annualInterestRate;
    }

    /**设置年利率的静态方法*/
    public static void setAnnualInterestRate(double annualInterestRate) {
        Account.annualInterestRate = annualInterestRate;
    }

    /**返回开户日期*/
    public Date getDateCreated() {
        return dateCreated;
    }
}


package pack1;

public class CheckingAccount extends Account{
    private static double limit;    //透支限定额

    public CheckingAccount() {
    }

    /**带指定账号、余额的构造方法*/
    public CheckingAccount(int id, double balance) {
        super(id, balance);
    }

    /**返回透支限定额的静态方法*/
    public static double getLimit() {
        return limit;
    }

    /**设置透支限定额的静态方法*/
    public static void setLimit(double limit) {
        CheckingAccount.limit = limit;
    }

    @Override   /**返回父类字符串、透支限定额的字符串*/
    public String toString() {
        return super.toString() + "\nLimit: " + limit;
    }
}




package pack1;

public class SavingAccount extends Account {
    public SavingAccount() {
    }

    public SavingAccount(int id, double balance) {
        super(id, balance);
    }
}




package pack1;

public class TestAccount {
    public static void main(String[] args) {
        Account account = new Account(1, 1000);
        CheckingAccount checkingAccount = new CheckingAccount(2, 12000);
        CheckingAccount.setLimit(200);
        CheckingAccount.setAnnualInterestRate(0.25);
        SavingAccount savingAccount = new SavingAccount(3, 2000);

        System.out.println(account + "\n");
        System.out.println(checkingAccount + "\n");
        System.out.println(savingAccount);
    }
}

举报

相关推荐

0 条评论