【发布时间】:2017-04-18 11:08:07
【问题描述】:
这是我的抽象类:
public abstract class BankAccount{
protected long balance;
public BankAccount(long balance){ \\<--Abstract class constructor
this.balance = balance;
}
... more stuff
}
我有以下子类(也是一个额外的子类 SavingsAccount,它们都有自己独立的余额,但这无关紧要):
public class CurrentAccount extends BankAccount{
private int PIN;
private long overdraft = 0;
private long balance;
// Set balance and overdraft and the PIN
public CurrentAccount(long balance, long overdraft, int PIN){
super(balance);
this.overdraft = overdraft;
setPIN(PIN);
}
// Set balance and overdraft
public CurrentAccount(long balance, long overdraft){
super(balance);
this.overdraft = overdraft;
}
// Set overdraft only
public CurrentAccount(long overdraft){ \\<-- is it possible to have something like this?
super(balance);
this.overdraft = overdraft;
}
public void setPIN(int PIN){
if(PIN >= 0000 && PIN <= 9999){
this.PIN = PIN;
}
}
... more methods
}
从上面可以看到,我想要一个只设置透支的构造函数,但是我仍然需要在每个构造函数的开头调用 super,所以我只是传入,无论当前余额是多少,我可以甚至这样做?还是我的 CurrentAccount 子类中也需要一个余额变量?
编译java时给我这个:
CurrentAccount.java:41: error: cannot reference balance before supertype constructor has been called
super(balance);
^
1 error
任何帮助将不胜感激。
【问题讨论】:
标签: java abstract-class super class-constructors