2016-04-14 42 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(); 
} 
相關問題