我有五个课程:
将为BankApp:
public class BankApp {
public static void main(String[] args) {
BankDatabase acctDatabase = new BankDatabase();
acctDatabase.createCheckingAccount("Test Name", "123-45-6789", 20000.0f);
acctDatabase.applyInterest();
acctDatabase.print();
}
}
BankDatabase:
import java.util.ArrayList;
import java.util.Collections;
public class BankDatabase {
ArrayList<BankAccount> list = new ArrayList<>();
public void createCheckingAccount(String name, String ssn, float bal) {
BankAccount account = new CheckingAccount(name, ssn, bal);
list.add(account);
}
public void createSavingsAccount(String name, String ssn, float bal) {
BankAccount account = new SavingsAccount(name, ssn, bal);
list.add(account);
}
public void print() {
Collections.sort(list, (BankAccount a, BankAccount b) -> {
return Float.compare(b.bal, a.bal);
});
for(int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
}
public abstract void applyInterest();
}
的BankAccount:
public abstract class BankAccount {
protected String name;
protected String ssn;
protected float bal;
private String account;
public BankAccount(String name, String ssn, float bal) {
name = this.name;
ssn = this.ssn;
bal = this.bal;
accountNumber();
System.out.println("Successfully created account for " + name + ". Account Number: " + account);
if(!ssn.matches("^(\\d{3}-?\\d{2}-?\\d{4})$")) {
System.out.println(name + " has an invalid SSN!");
}
System.out.println(name + ", Balance $" + bal);
}
@Override
public String toString() {
return "Name: " + name + ", Account #: " + account + ", Balance: $" + bal;
}
public abstract void applyInterest();
}
的CheckingAccount:
public class SavingsAccount extends BankAccount {
public SavingsAccount(String name, String ssn, float bal) {
super(name, ssn, bal);
}
@Override
public void applyInterest() {
bal = (float) (bal * 1.05);
}
}
和SavingsAccount:
public class CheckingAccount extends BankAccount {
public CheckingAccount(String name, String ssn, float bal) {
super(name, ssn, bal);
}
@Override
public void applyInterest() {
if(bal >= 10000.00) {
bal = (float) ((bal - 10000.00) * 1.02) + 10000;}
}
}
}
我想从BankApp调用applyInterest(),但我不能,因为BankDatabase不是抽象的。我无法使BankDatabase成为抽象,因为如果我这样做,那么我就无法实例化BankDatabase。所以,我的问题是:如何调用applyInterest()?
答案 0 :(得分:0)
BankDatabase中的那个方法不应该是抽象的。我想你想这样做:
public class BankDatabase {
private List<BankAccount> accounts = new ArrayList<>();
// Add a BankAccount; leave the type creation outside this method.
// Polymorphism is your friend; use it.
public void addAccount(BankAccount account) {
if (account != null) {
this.accounts.add(account);
}
}
public void applyInterest() {
for (BankAccount account : this.accounts) {
account.applyInterest();
}
}
}
其他几点:
答案 1 :(得分:-1)
您需要一种方法来返回您尝试将兴趣应用到的BankAccount。
因此,在您的BankAccounts列表中,您需要找到该帐户。 按ID或名称搜索。从那里,您在列表中调用搜索方法以返回银行帐户,然后您可以.applyInterest到它。