简体   繁体   English

Java-继承与构造函数错误

[英]Java - Inheritance & Constructors Error

I am getting an error when I compile my code due to an issue with my constructors. 由于构造函数的问题,我在编译代码时遇到错误。

Here is my parent class constructor: 这是我的父类构造函数:

   public BankAccount(final String theNameOfOwner, final double theInterestRate)
   {
      myName = theNameOfOwner;
      myInterestRate = theInterestRate;
      myBalance = 0;
      myMonthlyWithdrawCount = 0;
      myMonthlyServiceCharges = 0;
   }

Here is my child class constructor: 这是我的子类构造函数:

   public SavingsAccount(final String theNameOfOwner, final double theInterestRate)
   {
      BankAccount(theNameOfOwner, theInterestRate);
      myStatusIsActive = false;
      myWithdrawalCounter = 0;
   }

I am getting the following error: 我收到以下错误:

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

The error says that I require String,double parameters in my BankAccount call in my child constructor if i'm understanding this correctly. 该错误表明,如果我正确理解这一点,则我的子构造函数中的BankAccount调用中需要String,double参数。 The only problem is it looks like I have those parameters correct. 唯一的问题是看起来我的参数正确。 Any help/input would be greatly appreciated since I just started programming Java! 自从我开始编程Java以来​​,任何帮助/输入将不胜感激! Thank you! 谢谢!

That is not the way to call the superclass constructor. 那不是调用超类构造函数的方法。 The compiler thinks you're trying to call a method called BankAccount which doesn't exist. 编译器认为您正在尝试调用不存在的名为BankAccount的方法。 Because there is no explicit call to a superclass constructor, it attempts to insert the implicit call to the default superclass constructor, and that doesn't exist either, leading to the compiler error you see. 因为没有对超类构造函数的显式调用,所以它尝试将隐式调用插入默认的超类构造函数,并且该隐式调用也不存在,从而导致您看到编译器错误。

Use the super keyword to call a superclass constructor. 使用super关键字调用超类构造函数。 Change 更改

BankAccount(theNameOfOwner, theInterestRate);

to

super(theNameOfOwner, theInterestRate);

我认为导致错误的线上需要以下内容:

super(theNameOfOwner, theInterestRate);

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

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