简体   繁体   English

如何使用 transferTo() 方法在账户之间转账?

[英]How do I use the transferTo() method to transfer money between accounts?

I am supposed to Add the following method to allow BankAccounts to transfer money to another BankAccount.我应该添加以下方法以允许 BankAccounts 将钱转移到另一个 BankAccount。 Where would I add this method to make sure it works for all BankAccounts, including SavingsAccount and CheckingAccount?我应该在哪里添加此方法以确保它适用于所有 BankAccount,包括 SavingsAccount 和 CheckingAccount?

The method im supposed to use is transferTo(BankAccount destinationAccount, int transferAmount)我应该使用的方法是transferTo(BankAccount destinationAccount, int transferAmount)

public class BankAccount {


private String accountHolderName;
private String accountNumber;
private int balance;

public BankAccount(String accountHolder, String accountNumber) {
    this.accountHolderName = accountHolder;
    this.accountNumber = accountNumber;
    this.balance = 0;
}

public BankAccount(String accountHolder, String accountNumber, int balance) {
    this.accountHolderName = accountHolder;
    this.accountNumber = accountNumber;
    this.balance = balance;
}

public String getAccountHolderName() {
    return accountHolderName;
}

public String getAccountNumber() {
    return accountNumber;
}

public int getBalance() {
    return balance;
}

// Update the balance by using the DollarAmount.Plus method
public int deposit(int amountToDeposit) {
    balance = balance + amountToDeposit;
    return balance;
}

// Update the balance by using the DollarAmount.Minus method
public int withdraw(int amountToWithdraw) {
    balance = balance - amountToWithdraw;
    return balance;
}

public int transferTo(BankAccount destinationAccount, int transferAmount) {

    return balance;

}

} }

Assumptions:假设:

  1. This is only an exercise and not a real application for a bank.这只是一个练习,而不是银行的实际应用。
  2. SavingsAccount and CheckingAccount are subclasses of BankAccount SavingsAccount 和 CheckingAccount 是 BankAccount 的子类

The method transferTo can be implemented like the following: transferTo 方法可以如下实现:

public int transferTo(BankAccount destinationAccount, int transferAmount) {
    this.balance -= transferAmount;
    destinationAccount.deposit(transferAmount);
    return balance;
}

In a real world application you need to ensure that this operation will be always atomic and thread-safe.在现实世界的应用程序中,您需要确保此操作始终是原子的和线程安全的。 Additionally, using int for the balance is strongly not recommended.此外,强烈不建议使用int进行天平。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM