我正在构建使用继承的构造类,并且我在使用super()
时遇到了困难。我的InterestCalculator class
是CompoundInterest Class
的父级。我正在尝试使用复合兴趣类中的super()
。您的构造函数InterestCalculator采用 3个参数(Principal Amount,InterestRate和term)
我需要调用CompoundInterest
4 parameters
,我需要传递 3(PrincipalAmount,InterestRate和Term),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;
}
}
答案 0 :(得分: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(...)
(如果存在,必须是子类构造函数的第一行),将调用匹配的基类构造函数,并将使用参数来设置适当的字段。没有必要再尝试从子类中再次执行它。
答案 1 :(得分:0)
CompoundInterest
班有几个错误。
1 - 您必须调用superclasst构造函数。由于InterestCalculator
只有一个构造函数(double, double, int)
,因此您需要在CompoundInterest
构造函数的开头调用它。
2 - 您在super
上以错误的方式使用super.CompoundInterest
。 super
用于从超类访问方法。您必须将其重命名为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;
}