如何使用从另一个Java类返回的方法

时间:2015-02-04 04:12:28

标签: java class extends super

我在BankAccount.java'中使用了这种方法。类

  public double calculateInterest()
  {
    double myInterest = 0.0;
    if(myBalance > 0.0){
    myInterest = this.myBalance * (myInterestRate/12.0);
  }
  return myInterest;
}

我需要在我的其他类中使用此方法,例如:

SavingsAccount extends BankAccount

      if(this.myBalance > 0)
      {  
          System.out.println(calculateInterest());
          this.myBalance += super.calculateInterest();
          this.myBalance -= this.myMonthlyServiceCharges;
      }

为什么我不能

   this.myBalance += super.calculateInterest();

它返回0.0

什么时候应该返回0.4左右

任何帮助都会很棒,谢谢

如果我把这段代码放在我的SavingsAccount类

中,它会起作用
public double calculateInterest()
{
  double myInterest = 0.0;
  if(myBalance > 0.0){
     myInterest = this.myBalance * (myInterestRate/12.0);
  }
  return myInterest;
  }

但它并没有真正教会我如何正确使用抽象类

1 个答案:

答案 0 :(得分:0)

适合我。在这里,我使用以下

重现
public class BankAccount {

    protected double myBalance = 0;
    protected double myInterestRate = .6;

    public double calculateInterest() {
        double myInterest = 0.0;
        if (myBalance > 0.0) {
            double myInterestRate;
            myInterest = this.myBalance * (this.myInterestRate / 12.0);
        }
        return myInterest;
    }
}

然后......

public class SavingsAccount extends BankAccount {

    double myMonthlyServiceCharges = 1;

    public static void main(String[] args) {
        SavingsAccount sa = new SavingsAccount();
        sa.myBalance = 14;
        sa.doIt();
    }

    void doIt() {
        if (this.myBalance > 0) {
            System.out.println(super.calculateInterest());
            this.myBalance += super.calculateInterest();
            this.myBalance -= this.myMonthlyServiceCharges;
        }
    }

}

你可以尝试一下,看看它是否适合你?