这是我的超级课程
public class BankAccount
{
double balance;
public BankAccount(double initialBalance)
{
this.balance = initialBalance;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount)
{
balance -= amount;
}
public double getBalance()
{
return balance;
}
public void transfer(double amount, BankAccount other)
{
balance -= amount;
}
}
这是扩展它的类
public class CheckingAccount extends BankAccount
{
int transactionCount;
double fee;
public CheckingAccount(double initialBalance)
{
this.balance = initialBalance;
this.transactionCount = 0;
}
public void deposit(double amount)
{
balance += amount;
transactionCount += 1;
}
public void withdraw(double amount)
{
balance -= amount;
transactionCount += 1;
}
public void deductFees()
{
if(transactionCount > 3)
{
fee = 2.0*(transactionCount-3);
}
balance -= fee;
transactionCount = 0;
}
}
构造函数在超类中运行良好但是当我尝试扩展该类时,我得到的错误是构造函数无法应用于给定类型,即使我正在应用一个double,就像它在超类中一样。我刚开始学习类中的继承,所以非常感谢任何输入
答案 0 :(得分:2)
您需要使用super
关键字来调用父级的构造函数。你的父类在没有传递给它的参数的情况下不会被定义,所以你可以这样做:
public CheckingAccount(double initialBalance) {
super(initialBalance);
this.transactionCount = 0;
}
答案 1 :(得分:0)
您的情况是您没有在超类中定义默认构造函数。如果您将添加以下构造函数,则不会出现错误。
public BankAccount(){
//default constructor
}
当您尝试实例化您的子类时,implisitly将首先被称为您的超类的默认构造函数。所以,你可以像我说的那样在你的BankAccount中添加默认的consturctor,并在里面写
public BankAccount() {
System.out.println("loading superclass default");
}
在你的子类中写
public CheckingAccount(double initialBalance) {
System.out.println("loading subclass");
this.balance = initialBalance;
this.transactionCount = 0;
}
然后尝试
CheckingAccount acc = new CheckingAccount(52);
你会看到结果:
loading superclass default
loading subclass