【发布时间】:2018-10-13 14:10:24
【问题描述】:
这只是我第二次使用它,也是我第一次得到很好的帮助,所以我希望我能得到更多的帮助!
背景:
我的程序通过创建一个持有余额和其他东西的对象来测试我的Account 类。说明说我需要重写子类的 "Withdraw" 和 "Deposit" 方法以跟踪交易。
我这样做了,但它不使用当前余额,而只是发送一个 0。我希望能够保留新余额,以便它实际从当前余额中提取或存款。
对不起,如果这没有意义,如果需要任何澄清,我会尝试以不同的方式解释。
下面是我的代码 sn-p:
注意:我保留了与此无关的东西(构造函数和其他方法):
Account.java
public class Account
{
private static double balance;
public void Withdraw(double withdrawAmount)
{
this.balance -= withdrawAmount;
}
public void Deposit(double depositAmount)
{
this.balance += depositAmount;
}
}
UserAccount.java
public class UserAccount extends Account
{
private ArrayList<Transactions> transactions = new ArrayList();
@Override
public void Withdraw(double withdrawAmount)
{
super.Withdraw(withdrawAmount);
Transactions thisTransaction = new Transactions('W',
withdrawAmount, this.AccBalance(), "Withdraw");
this.transactions.add(thisTransaction);
}
@Override
public void Deposit(double depositAmount)
{
super.Deposit(depositAmount);
Transactions thisTransaction = new Transactions('D',
depositAmount, this.AccBalance(), "Deposit");
this.transactions.add(thisTransaction);
}
public void fillTransactions(char type, double amount, double balance)
{
switch (type) {
case 'D':
this.Deposit(amount);
break;
case 'W':
this.Withdraw(amount);
break;
default:
System.out.println("ERROR fillTransactions");
break;
}
}
public static void main(String[] args) {
ArrayList<Transactions> copyTransactions;
UserAccount thisAccount = new UserAccount("George", 1122, 1000);
thisAccount.MutAIR(.015);
thisAccount.fillTransactions('D', 30, thisAccount.AccBalance());
thisAccount.fillTransactions('D', 40, thisAccount.AccBalance());
thisAccount.fillTransactions('D', 50, thisAccount.AccBalance());
thisAccount.fillTransactions('W', 5, thisAccount.AccBalance());
thisAccount.fillTransactions('W', 4, thisAccount.AccBalance());
thisAccount.fillTransactions('W', 2, thisAccount.AccBalance());
}
我拥有的Transactions 类拥有类型(取款或存款)、取款或存款的金额以及余额。发生的情况是,当我从覆盖的存款或取款方法中调用超类时,它将余额设置为 0,因此当我想要存款或取款货币的原始余额时,它表示余额为 50、40 或 -5。
如果有人可以提供帮助,那就太棒了!我可以澄清是否有任何令人困惑的地方!谢谢!
【问题讨论】:
-
几件事 1.
fillTransactions中的balance参数未使用。您确定要使用此参数吗? 2. 你的UserAccount.AccBalance()函数是什么样子的。 3.balanceinAccount不应该是静态的,因为您可能希望它对于Account的每个实例都不同 -
指令声明它希望我的 getter 和 setter 是静态的,所以为了让编译器不会对我尖叫,我将它设置为静态。我的代码看起来像这样用于访问平衡。它基本上是一个 getter,只是缩写为 public static double AccBalance() { return balance; }
-
函数
AccBalance和balance不应该是静态的恕我直言。我希望你知道 Java 中静态变量和非静态变量的区别 -
只是好奇,这是作业题吗?
-
我确实知道其中的区别,这就是为什么我对为什么我的教授希望它全部是静态的感到困惑。它使这变得如此混乱,我不知道如何解决静态问题。关于如何解决它的任何想法。复印一份?
标签: java methods overriding super