2016-04-14 61 views
0

如何让同一类别的两个对象使用不同的利率?将两组不同利率应用于同一类别的两个对象

我需要这样做,以便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))); 

目前我使用分配给它们的double值的变量,但这当然意味着这两个对象(savingAccount2和savingAccount3)都使用相同的数字。请注意,这些变量都存储在Account.java超像这样:

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

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

回答

1

可以在类账户编写方法来设置低速率和高速编译码的值,如:当你创建类SavingsAccount的对象

public void setRates(double lr, double hr){ 
     lowRate=lr; 
     highRate=hr; 
} 

现在,你可以这样做:

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

已排序。这个答案解决了我的问题,因为它更容易理解并实施到我的程序中。感谢您的知识和时间。 –

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()方法,它会考虑通过的值。

+0

这看起来像我正在研究的东西。我将尝试尽快实施,并回到您身边,因为我目前正在使用移动电话远离计算机。从我所看到的,看起来很难实施 –

+0

这非常简单。使用构造函数是您将在Java中执行的每日活动。只要记住你会在你的实例中调用你的方法,比如'savingAccount1.interest()','savingAccount2.interest()'等等......只要知道是否有什么不清楚。 – dambros

+0

好吧,所以我理解变量的一部分......下面的一点让我很难说实话。我只是不知道如何将它实现到我的程序中,因为当我尝试时,我收到很多警告错误。例如,当我将代码的第二部分添加到我的帐户类中时,我在我的savingAccountUI1类中收到警告错误。具体而言,它与我的 问题“公开savingAccount1UI(){ 的initComponents();) updatebalance(; }” @dambros –

0

只要做到这一点:

savingAccount1UI savingAccount2 = new savingAccount1UI(0.019,0.025); 

类定义:

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

计算过程,当也是类的方法和访问内部件价值。

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(); 
} 
相关问题