-1

我正在制作使用继承的 Construct 类,但我很难使用super(). 我有InterestCalculator class那个是CompoundInterest Class. 我正在尝试super()在 Compound Interest 类中使用。您的构造函数 InterestCalculator 需要3 个参数(本金金额、利息率和期限) 我需要调用CompoundInterest哪个参数4 parameters并且我需要传递3 个(PrincipalAmount、InterestRate 和期限)并且4th parameter是特定于CompoundInterest.

import java.util.Scanner;
public class InterestCalculator
{

  protected double principalAmount;
  protected double interestRate;
  protected int term;

  public InterestCalculator(double principalAmount, double interestRate,          int term)
  {
     this.principalAmount = principalAmount;
     this.interestRate= interestRate;
     this.term = term;
  }   
  public double getPrincipal()
  {
      return principalAmount;
  }       
  public  double getInterestRate()
  {
     return interestRate;
  }
  public  double getTerm()
  {
     return term;
  }
  public double calcInterest()
  {
     return -1;
  }
  protected double convertTermToYears()
  {
    return (this.term / 12.0);
  }
  protected double convertInterestRate()
  {
    return (this.interestRate / 100.0);
  }
}
public class CompoundInterest extends InterestCalculator
{
  protected int compoundMultiplier = 0;       

  super.CompoundInterest(double compoundMultiplier);
  {
    super.principalAmount = principalAmount;
    super.interestRate = interestRate;
    super.term = term;
    this.compoundMultiplier = (int) compoundMultiplier; 
  }
  public double calcInterest()
  {
    double calcInterest = (super.principalAmount *Math.pow((1.0+((super.convertInterestRate())/this.compoundMultiplier)),(this.compoundMultiplier *(super.convertTermToYears()))))- super.principalAmount;              
    return calcInterest;    
  }
}
4

2 回答 2

1

您需要在派生类中定义一个构造函数,该构造函数接受它需要的所有参数:

public class CompoundInterest extends InterestCalculator {
    protected int compoundMultiplier;

    /**
     * Constructor for CompoundInterest.
     */
    public CompoundInterest(double principalAmount, double interestRate, int term,
        int compoundMultiplier)
    {
        super(principalAmount, interestRate, term);
        this.compoundMultiplier = compoundMultiplier;
    }

    . . . // rest of class
}

请注意,在构造函数内部,super(...)调用超类构造函数。你不能通过super.在你的构造函数名称前面加上这个来做到这一点。通过调用super(...)(如果存在,必须是子类构造函数的第一行),匹配的基类构造函数将被调用并使用参数来设置适当的字段。没有必要从子类再次尝试这样做。

于 2013-05-07T03:30:40.817 回答
0

CompoundInterest门课有几个错误。

1 - 您必须调用超类构造函数。由于InterestCalculator只有一个构造函数(double, double, int),因此您需要在CompoundInterest构造函数的开头直接调用它。

2 - 你super在错误的方式上使用super.CompoundInterestsuper用于访问超类中的方法。您必须将其重命名为CompoundInterest.

3 - 如第一项所述,您需要从超类调用构造函数。你这样做:super(principalAmount, interestRate);. 请记住:它必须是构造函数的第一次调用。

4 - 您没有传递给CompountInterest它所期望的三个参数中的任何一个。您应该考虑将这些参数也放入其中CompoundInterest

如果您应用这些更改,您的代码将如下所示:

CompoundInterest(double compoundMultiplier, double principalAmount, double interestRate, int term); {
    super(principalAmount, interestRate, term);
    this.compoundMultiplier = (int) compoundMultiplier; 
}
于 2013-05-07T03:38:51.260 回答