Java - 继承和构造函数错误

标签 java inheritance types constructor

由于构造函数存在问题,我在编译代码时收到错误。

这是我的父类构造函数:

   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/

相关文章:

Java 泛型 Comparable,其中子类无法相互比较

java - 无法从 Java 程序调用批处理文件

c# - 通用继承和委托(delegate)

c++ 以此类为类型继承类模板

c# - 反射和继承问题c#

c# - 给定一个类型,如何确定它装箱的类型?

c++ - 不简单,从 char[8] 转换 long long

Java流按键和值对映射进行排序

java - Wicket validator 不会对空字段值引发错误

C# 获取给定 T 的类型 Generic<T>