将两组不同的利率应用于同一类的两个对象

时间:2016-04-14 14:45:37

标签: java

如何让同一个班级的两个对象使用不同的利率?

我需要这样做,以便savingAccount2和savingAccount3使用不同的利率。

savingAccount1UI savingAccount2 = new savingAccount1UI();
savingAccount1UI savingAccount3 = new savingAccount1UI();

这些对象都从名为Account.java的类继承。此超类包含包含如何计算兴趣的所有方法。

以下是超类中计算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超类中,如下所示:

public double lowRate = 0.019;
public double highRate = 0.025;

我想我可能需要为每个对象使用构造函数,并使用预设值来解决我的问题,但我不明白如何实现这个想法。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

您可以在类Account中编写方法来设置lowRate和highRate的值,如:

SavingsAccount sa=new SavingsAccount();
sa.setRates(0.019,0.025);

现在,当您创建类SavingsAccount的对象时,您可以执行以下操作:

@IBOutlet

答案 1 :(得分:0)

看来你正在寻找这个:

public class Account {

    private double lowRate;
    private double highRate;
    //other fields

    public Acount(double lowRate, double highRate) {
        this.lowRate = lowRate;
        this.highRate = highRate;
    }

    // your interest() method
    // getters & setters
}

public class SavingAccount1UI extends Account {

    public SavingAccount1UI(double lowRate, double highRate) {
        super(lowRate, highRate);
    }

    // rest of your stuff
}

这样,您只能创建一个传递所需值的对象,例如:

SavingAccount1UI savingAccount = new SavingAccount1UI(0.019, 0.025);

现在每次调用interest()方法时,都会考虑传递的值。

答案 2 :(得分:0)

就这样做:

savingAccount1UI savingAccount2 = new savingAccount1UI(0.019,0.025);

在课程定义中:

savingAccount1UI(float lowRate,float highRate) {
    this.lowRate = lowRate;
    this.highRate = highRate;
}

计算时也将类传递给方法并访问inners值。

public void interest(double interest,savingAccount1UI account){
  if(balance<target){

      interest = balance*account.lowRate; 
      balance = balance + interest;
      updatebalance();
  } else{
      interest=balance*account.highRate;
      balance = balance + interest;  
  }  
  updatebalance();
}