我练习Java,我似乎在网上找到的练习练习有困难:
我需要:
帐户类:
public class Account {
protected double balance;
Account(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
balance = balance - amount;
}
public double getBalance() {
return balance;
}
}
我的交易尝试类:
public class Transactions extends Account {
int numOftransactions;
public Transactions(double initialValue) {
super.balance = initialValue;
numOftransactions = 0;
}
}
答案 0 :(得分:1)
public class Transactions extends Account {
int n; //in java there's a difference between int and Integer btw
public Transactions( double initialBalance ) {
super( initialBalance ); //this is how you call the super class' constructor
//the super class being Account
n = 0;
}
}
编辑: 至于改变平衡,你真的不需要改变它来保护。帐户为您提供了修改余额的方法。你只需要覆盖Transactions中的方法,并在将n递增1之前调用这些方法:
public class Transactions extends Account {
...
//by naming the method the same name, we overwrite the one in Account
public void deposit(double amount) {
//first call Account's deposit
super.deposit( amount ); //this will call Account's version of deposit
n++;//increment n by 1
}
}
您可以以类似的方式覆盖所有帐户的方法,以便每次都增加交易次数。
答案 1 :(得分:0)
balance
的访问修饰符更改为protected。当你不需要时,不要增加可见度。super(initialBalance);
)。现在,Java编译器将向超类构造函数添加一个没有参数的调用,因为您没有明确地这样做。你可能在这里遇到了错误。删除您尝试更改超类的位置'平衡;这是不必要的,会提高知名度。super(amount);
)的调用,然后将n增加1。也许还为numOfTransactions
添加了一个getter。numOfTransactions
的访问修饰符更改为private而不是package-private(默认值)。就我个人而言,我也将子类命名为TransactionAccount
或类似地,Transactions
直觉上听起来不太正确。