如何使同一类的两个对象使用不同的利率?
我需要让 savingAccount2 和 savingAccount3 使用不同的利率。
savingAccount1UI savingAccount2 = new savingAccount1UI();
savingAccount1UI savingAccount3 = new savingAccount1UI();
这些对象都继承自一个名为 Account.java 的类。该父类(super class)包含所有方法,包括如何计算利息。
这是父类(super class)中计算 1 年利息的当前方法account.java:
//add interest
public void interest(double interest){
if(balance<target){
interest = balance*lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*highRate;
balance = balance + interest;
}
updatebalance();
}
这是触发此方法的按钮:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
interest(Float.parseFloat(balanceLabel.getText().substring(1)));
目前我使用的变量分配有双值,但这当然意味着两个对象( savingAccount2 和 savingAccount3 )使用相同的数字。请注意,这些变量存储在 Account.java 父类(super class)中,如下所示:
public double lowRate = 0.019;
public double highRate = 0.025;
我想我可能需要为每个对象使用一个构造函数,并使用预设值来解决我的问题,但我不明白如何实现这个想法。有什么建议吗?
最佳答案
您可以在类 Account 中编写方法来设置 lowRate 和 highRate 的值,如下所示:
public void setRates(double lr, double hr){
lowRate=lr;
highRate=hr;
}
现在,当您创建 SavingsAccount 类的对象时,您可以执行以下操作:
SavingsAccount sa=new SavingsAccount();
sa.setRates(0.019,0.025);
关于java - 对同一类别的两个对象应用两组不同的利率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36626598/