好的伙计们,我在这些代码和一些逻辑上遇到了这些构造函数的问题。我完成了大部分工作,只是对如何完成此操作感到困惑。
这是我的主要代码。 (它可能有点草率,但它“足够好”)
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;
}
}
现在,我想创建一个储蓄和支票帐户。我需要帮助我需要为构造函数添加的内容,我在注释中添加了我知道的部分,但我对此缺失感到困惑。
节约:
class Savings extends Account{
//need to create a constructor
public Savings(int id, double balance, double annualInterestRate) {
//need to invoke the constructor for Account
super(id, balance, annualInterestRate);
}
// need to override the withdraw method in Account
public void withdraw(double amount) {
// place logic to prevent the account from being overdrawn
// that is do not allow a negative balance
}
}
答案 0 :(得分:1)
你只需要检查id的数量<平衡或者你拥有的任何逻辑(例如:你想要的) 帐户中存在一些阈值金额。)
此外,我建议您查看同步方法,因为您应该同步访问给定用户的帐户,以确保在调用撤销功能时...同一用户帐户的另一个撤销必须等待......否则它会导致问题...我会留给你弄清楚。
public void withdraw(double amount) {
// place logic to prevent the account from being overdrawn
// that is do not allow a negative balance
if(balance < amount)
{
// print error message or do something
}
else
{
// withdraw the money
balance -= amount;
// print message or do something
}
}
答案 1 :(得分:1)
super()
在Savings
案例Account
中调用超类的构造函数。