繁体   English   中英

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

[英]How to use method return from another Java class

我在'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;
  }

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

为我工作。 在此我复制以下内容

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;
        }
    }

}

您可以尝试一下,看看是否适合您吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM