0

If I have an array of an object that has subclasses, can I access methods in the subclasses through calling the array?

This is a method in my Banking class, I would like to set the checking:

public void deposit() throws IOException {
BufferedReader br;
String entered_amount;

System.out.print("How much would you like to deposit? :");
br = new BufferedReader(new InputStreamReader(System.in));
entered_amount = br.readLine();
double amount = Double.valueOf(entered_amount).doubleValue();
balance = balance + amount;

System.out.println("Your balance is: " + getBalance());

Here is my Checking class:

public class Checking extends Bankaccount {

private double balance;

public Checking() {
}

public Checking(double balance) {
    this.balance = balance;
}

/**
 * @return the balance
 */
public double getBalance() {
    return balance;
}

/**
 * @param balance the balance to set
 */
public void setBalance(double balance) {
    this.balance = balance;
}

}

When calling baArray[0] in my main class is there a way to make deposit set the value of balance within the checking class?

The reason I'm doing this is because I'm writing out the array of objects to a file and rereading them when the program starts. I need to be able to store 3 sets of checking and savings. My deposit method would be what i'm trying to edit to use inheritance to set the balance in checking.

4

1 回答 1

1

添加到您的Banking班级:

public abstract setBalance(double balance);

如果你有subclasses一个方法没有意义Banking的类,那么你可以实现该方法并简单地让它抛出一个异常。(不过,一个类也有一个方法似乎是有意义的。)CheckingsetBalanceSavingssetBalance

或者,您可以将Checking'ssetBalance方法向上移动到 superclass Banking,然后CheckingSavings将继承该setBalance方法。如果你需要覆盖它们,你可以,没问题。

编辑:根据对此答案的评论,我现在更清楚您要完成什么。

如果您打算拥有一个Banking对象数组,并且每个对象都有一些唯一的帐号,并且对于每个Bank帐户,都有一个Checking帐户和一个Savings帐户,那么从逻辑上讲,听起来对于CheckingSavings成为private类更有意义只能通过Banking类访问。

因此,当帐户持有人去银行时,他们会开设一个Banking帐户。也许默认情况下,这带有 1 个Checking帐户和 1 个Savings帐户。这些将是您Banking班级中的班级变量:

private Checking checking;
private Savings savings;

现在您的Banking班级需要公共方法来访问支票和储蓄账户。

假设你的CheckingandSavings类都有一个getBalanceand setBalance。现在你的Banking类需要为每种类型的帐户一个setter& getter,它只调用适当的方法。

例如,在您的Banking班级中:

public void setCheckingBalance(double balance)
{
    checking.setBalance(balance);
}

public double getCheckingBalance()
{
    return checking.getBalance();
}

然后在您的主要方法中,您将通过以下方式使用这些方法:

baArr[0].setCheckingBalance(100.00);
于 2013-10-27T04:07:31.287 回答