创建子类

时间:2014-02-26 19:54:22

标签: java subclass

我必须使用定义为银行帐户建模的帐户创建一个类。 (该帐户具有物业帐号,余额,年利率,创建日期以及存入/取出资金的方法。)

我如何创建两个子类来检查和保存帐户?支票账户必须有透支限额,但节省的金额不能过高。

任何帮助或建议都会很棒,谢谢(

public class Accountdrv {
  public static void main (String[] args) {
    Account account = new Account(1122, 20000, 4.5);

    account.withdraw(2500);
    account.deposit(3000);
    System.out.println("Balance is " + account.getBalance());
    System.out.println("Monthly interest is " +
      account.getMonthlyInterest());
    System.out.println("This account was created at " +
      account.getDateCreated());
  }
}

class Account {
  private int id;
  private double balance;
  private double annualInterestRate;
  private java.util.Date dateCreated;

  public Account() {
    dateCreated = new java.util.Date();
  }

  public Account(int id, double balance, double annualInterestRate) {
    this.id = id;
    this.balance = balance;
    this.annualInterestRate = annualInterestRate;
    dateCreated = new java.util.Date();
  }

  public int getId() {
    return this.id;
  }

  public double getBalance() {
    return balance;
  }

  public double getAnnualInterestRate() {
    return annualInterestRate;
  }

  public void setId(int id) {
    this.id =id;
  }

  public void setBalance(double balance) {
    this.balance = balance;
  }

  public void setAnnualInterestRate(double annualInterestRate) {
    this.annualInterestRate = annualInterestRate;
  }

  public double getMonthlyInterest() {
    return balance * (annualInterestRate / 1200);
  }

  public java.util.Date getDateCreated() {
    return dateCreated;
  }

  public void withdraw(double amount) {
    balance -= amount;
  }

  public void deposit(double amount) {
    balance += amount;
  }
}

1 个答案:

答案 0 :(得分:0)

考虑定义一个或多个接口。 例如:

public interface Account
{
    public double getAnnualInterestRate();
    public Date getDateCreated();
    public int getId();
    public double getMonthlyInterest();

    public void deposit(double amount);
    public void withdraw(double amount);
}

public interface CheckingAccount
extends Account
{
    public long getOverdraftLimit();
}

添加setter可能是合理的,但我更喜欢在实现类构造函数中设置vlues,或者将setter放在实现类中,而不是在接口中。一个合理的异常可能是CheckingAccount接口中的setOverDraftLimit()。

你犯了一些常见的金钱错误:

  • 钱不是浮点值。它是一个固定点值。 double永远不会对钱有所帮助。请改用long并存储为单位的分数(例如10000 = 1美元)。
  • 了解如何执行兴趣计算。年利率永远不会是12 *月利率。