由于构造函数存在问题,我在编译代码时收到错误。
这是我的父类构造函数:
public BankAccount(final String theNameOfOwner, final double theInterestRate)
{
myName = theNameOfOwner;
myInterestRate = theInterestRate;
myBalance = 0;
myMonthlyWithdrawCount = 0;
myMonthlyServiceCharges = 0;
}
这是我的子类构造函数:
public SavingsAccount(final String theNameOfOwner, final double theInterestRate)
{
BankAccount(theNameOfOwner, theInterestRate);
myStatusIsActive = false;
myWithdrawalCounter = 0;
}
我收到以下错误:
SavingsAccount.java:7: error: constructor BankAccount in class BankAccount cannot be applied to given types;
{
^
required: String,double
found: no arguments
reason: actual and formal argument lists differ in length
该错误表明,如果我理解正确的话,我在子构造函数中的 BankAccount 调用中需要 String,double 参数。唯一的问题是我的这些参数看起来是正确的。任何帮助/输入将不胜感激,因为我刚刚开始编程 Java!谢谢!
最佳答案
这不是调用父类(super class)构造函数的方法。编译器认为您正在尝试调用一个不存在的名为 BankAccount
的方法。由于没有对父类(super class)构造函数的显式调用,因此它尝试插入对默认父类(super class)构造函数的隐式调用,而该调用也不存在,从而导致您看到的编译器错误。
使用super
关键字调用父类(super class)构造函数。改变
BankAccount(theNameOfOwner, theInterestRate);
至
super(theNameOfOwner, theInterestRate);
关于Java - 继承和构造函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31544936/