2015-07-21 282 views
0

由于构造函数的问题,我编译代码时出现错误。Java - 继承与构造函数错误

这里是我的父类的构造函数:

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 

错误说我需要String,在我的子构造函数的BankAccount调用中的双参数,如果我正确理解这一点。唯一的问题是它看起来像我有这些参数是正确的。任何帮助/输入将不胜感激,因为我刚开始编程Java!谢谢!

+0

尝试的超代替父类的名称 – Renjith

+0

https://开头docs.oracle.com/javase/tutorial/java/IandI/super.html –

回答

3

这不是调用超类构造函数的方法。编译器认为你正试图调用一个不存在的名为BankAccount的方法。由于没有对超类构造函数的显式调用,因此它会尝试将隐式调用插入到默认的超类构造函数中,并且该函数也不存在,从而导致出现编译器错误。

使用super关键字来调用超类的构造函数。更改

BankAccount(theNameOfOwner, theInterestRate); 

super(theNameOfOwner, theInterestRate); 
+0

我明白了!我从来不知道这一点。我在课堂上一直没有引起足够的重视。非常感谢您的先生/女士。 – Trafton

1

我认为你需要对导致错误的线是什么,而不是如下:

super(theNameOfOwner, theInterestRate);