java 创建两个子类用于支票和储蓄账户。支票账户有透支限额,但储蓄账户不能透支

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35494039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:11:42  来源:igfitidea点击:

Create two subclasses for checking and saving accounts. A checking account has an overdraft limit but a savings account cannot be overdrawn

javasubclassabstract

提问by Ben

Account class was defined to model a bank account. An account has the properties account number, balance, annual interest rate, and date created, and methods to deposit and withdraw funds.

帐户类被定义为模拟银行帐户。帐户具有属性帐号、余额、年利率和创建日期,以及存取资金的方法。

Now Create two subclasses for checking and saving accounts. A checking account has an overdraft limit(say $1,000 with a $25 fee charged), but a savings account cannot be overdrawn.

现在为支票和储蓄账户创建两个子类。支票账户有透支限额(比如 1,000 美元,收取 25 美元的费用),但储蓄账户不能透支。

Write a test program that creates objects of Account, SavingsAccount, and CheckingAccount and invokes their toString() method.

编写一个测试程序,创建 Account、SavingsAccount 和 CheckingAccount 的对象并调用它们的 toString() 方法。

Above are the instructions and below is my code. I cannot figure out how to invoke the subclasses into the main Account Class. I would also like to know how the toString() method can be applied because I cannot get that either. I also kept most of my comments in my code where I was trying different ideas.

上面是说明,下面是我的代码。我不知道如何将子类调用到主帐户类中。我还想知道如何应用 toString() 方法,因为我也无法得到它。我还将大部分评论保留在我尝试不同想法的代码中。



/* 

//Calls both subclasses to the main. As well as a few other variables.  
SavingsAccount savings = new SavingsAccount();
CheckingAccount checking = new CheckingAccount();
Account account;


    double balance = 0.0;
    double withdrawal = 0.0;
    double deposit = 0.0;

    System.out.println(checking);
    CheckingAccount.getwithdrawal(10.50);
    System.out.println(savings);
    SavingsAccount.deposit(5.0);
    System.out.println(account);
     }    
}

 */

 package account;



  public class Assignment5  {

   SavingsAccount savings = new SavingsAccount();
   CheckingAccount checking = new CheckingAccount();
   Account account;

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

  /* System.out.print("After Creation,  " );
   Print (account.getBalance());
  Account.setAnnualInterestRate(4.5);
   System.out.print("After Withdrawal of ,500,  " );
   account.withdraw(2500);
   Print (account.getBalance());
    System.out.print("After Deposit of ,000,  " );
    account.deposit(3000);
   Print (account.getBalance());
    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()); */

    } 
  // Extra Print Method
     public static void Print (double x){
     System.out.printf("The current balance is "+" $ "+"%4.2f"+"%n",x);
    }
  }



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

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

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

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

   public double getBalance() {
    return balance;
    }

     public static double getAnnualInterestRate() {
      return annualInterestRate;
      }

    public void setId(int newId) {
     id = newId;
     }

    public void setBalance(double newBalance) {
     balance = newBalance;
     }

  public static void setAnnualInterestRate(double newAnnualInterestRate) {
    annualInterestRate = newAnnualInterestRate;
  }

 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;
   }
  }


 package account;

 public class CheckingAccount extends Account {


double overDraft = -1000;

    public void checking(double i) {

        //initializes double variable balance as 0.0
        double balance = 0.0;
        if (balance - i < overDraft){
                System.out.println("Failure: Can't overdraft more than            ,000. A  +"
                        + "overdraft fee will be issued to your account. ");
             balance = balance - 25; }
        else
            balance = balance - i;
      }   
  }


  package account;

  public class SavingsAccount extends Account{
    double overdraftLimit = 0;

    public void withdraw (double w) {
        if (balance - w < overdraftLimit)
                System.out.println("Insufficient Funds");
        else
            balance = balance - w;
    }
}

回答by Untitled123

I'm not sure what you mean by invoking subclasses, but the signature for the toString method is

我不确定调用子类是什么意思,但是 toString 方法的签名是

public String toString(){
}

Since everything is virtual in Java by default, then simply have that method in the subclasses to override it. From what I can guess, it seems like the question wants you to call the various methods in the toString method and return a complete string of all the information needed.

由于默认情况下 Java 中的所有内容都是虚拟的,因此只需在子类中使用该方法即可覆盖它。据我所知,这个问题似乎希望您调用 toString 方法中的各种方法并返回包含所有所需信息的完整字符串。

On another note, to call a superclass method even if the subclass overrides it in Java, the syntax is

另一方面,要调用超类方法,即使子类在 Java 中覆盖了它,语法是

super.function()

回答by tmaxxcar

first, you need to create the default constructor for a savings account and checking account. Then you need to create an overloaded constructor (assuming you will be passing unique extra values into the subclasses)

首先,您需要为储蓄账户和支票账户创建默认构造函数。然后你需要创建一个重载的构造函数(假设你将唯一的额外值传递给子类)

 public savingsAccount() {
super();
}
//overloaded constructor
public savingsAccount(int newId, double newBalance, int anotherVariable ) {
 super(newID, newBalance);
 this.anotherVariable = anotherVariable; //this is unique to this specific class

}

As for toString(), you need each subclass to have its own.

至于 toString(),您需要每个子类都有自己的子类。

String toString(){
 String x = "Savings: " + totalSavings + ". And the fee's assessed are: " + fees";
  return x;
}

This will allow you to call savingsAccount.toString();which will print the information.

这将允许您调用savingsAccount.toString();将打印信息。

回答by Jennifer Nghi Nguyen

You need to override the default toString method of each class For example, in Account class

需要重写每个类的默认toString方法 例如在Account类中

    @Override
    public String toString()
    {
        String str = "Id: "+ getId() +
                     "\nBalance:  " + getBalance()+
                     "\nAnnual Interest Rate: " + getAnnualInterestRate() +
                     "\n Monthly Interest: " + getMonthlyInterest() +
                     "\n Created on: " + getDateCreated();

        return str;
    }

Then, create Account object in main class

然后,在主类中创建 Account 对象

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Account account = new Account(1122, 20000);
    System.out.println(account); // invoke toString method in Account class
}

the result will be: Id: 1122 Balance: 20000.0 Annual Interest Rate: 0.0 Monthly Interest: 0.0 Created on: Thu Feb 18 15:16:47 PST 2016

结果将是:Id:1122 余额:20000.0 年利率:0.0 月利率:0.0 创建时间:2016 年 2 月 18 日星期四 15:16:47 PST

Similarly, You need to override toString method for subclass also. But you need to connect superclass's toString by using super keyword:

同样,您还需要为子类覆盖 toString 方法。但是你需要使用 super 关键字连接超类的 toString :

public String toString()
{
    String str=super.toString();// call superclass's toString()
    str+="...";
    return str;
}