我对如何从子类中的类重写方法感到困惑。我目前有一个使用子帐户创建的帐户类(检查帐户和储蓄帐户)。我知道我需要编辑撤销方法以允许在检查中透支一定数量,并且不允许在节省中进行透支。我很难将withdraw方法带入子类来编辑它们。我该怎么做?
当前代码
import java.util.Date;
public class Exercise_03
{
public static void main(String[] args)
{
//Account account = new Account(1122, 20000, .045);
Account checkingAccount = new CheckingAccount (1500, 100.00, 0.6);
java.util.Date dateCreated = new java.util.Date();
System.out.println("Checking Account ID: " + checkingAccount.id);
System.out.println("Balance: $" + checkingAccount.balance);
System.out.println("Balance after withdraw of $80: $" + checkingAccount.withdraw(80));
//System.out.println("Overall Account ID: " + account.id);
//System.out.println("Date Created: " + dateCreated);
//System.out.println("Balance: $" + account.getBalance());
//System.out.println("Interest Rate: " + account.getAnnualInterestRate() + "%");
//System.out.println("Monthly Interest: $" + account.getMonthlyInterestRate());
//System.out.println("Balance after withdraw of $2,500: $" + account.withdraw(2500));
//System.out.println("Balance after deposit of $3,000: $" + account.deposit(3000));
}
//Create Account Class
public static class Account
{
//Define Variables
public int id;
public double balance; // Account Balance
public double annualInterestRate;// Store Interest Rate
private Date dateCreated; // Stores Account Creation Date
// Account Constructor
Account ()
{
id = 0;
balance = 0.0;
annualInterestRate = 0.0;
}
// Account Constructor with id and initial balance
Account(int newId, double newBalance)
{
id = newId;
balance = newBalance;
}
Account(int newId, double newBalance, double newAnnualInterestRate)
{
id = newId;
balance = newBalance;
annualInterestRate = newAnnualInterestRate;
}
// Methods for id, balance, and annualInterestRate
public int getId()
{
return id;
}
public double getBalance()
{
return balance;
}
public double getAnnualInterestRate()
{
return annualInterestRate * 100;
}
public void setId(int newId)
{
id = newId;
}
public void setBalance(double newBalance)
{
balance = newBalance;
}
public void setAnnualInterestRate(double newAnnualInterestRate)
{
annualInterestRate = newAnnualInterestRate;
}
// Accessor method for dateCreated
public void setDateCreated(Date newDateCreated)
{
dateCreated = newDateCreated;
}
// Define method getMonthlyInterestRate
double getMonthlyInterestRate()
{
return (annualInterestRate/12) * balance;
}
// Define method withdraw
double withdraw(double amount)
{
return balance -= amount;
}
// Define method deposit
double deposit(double amount)
{
return balance += amount;
}
}
//Create Checking Account
public static class CheckingAccount extends Account
{
CheckingAccount (int id, double balance, double annualInterestRate)
{
super(id, balance, annualInterestRate);
}
//Create Savings Account
public class SavingsAccount extends Account
{
//SavingsAccount constructor
public SavingsAccount (int id, double balance, double annualInterestRate)
{
super(id, balance, annualInterestRate);
}
}
}
}