这是我的抽象类:
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
}
从上面可以看出,我想要一个只设置 overdraw 的构造函数,但我仍然需要在每个构造函数的开头调用 super,所以我只是传入,无论当前余额是多少,我可以吗甚至这样做?或者我的 CurrentAccount 子类中还需要一个余额变量吗?
编译 java 时给了我这个:
CurrentAccount.java:41: error: cannot reference balance before supertype constructor has been called
super(balance);
^
1 error
如有任何帮助,我们将不胜感激。
最佳答案
如果父类没有默认(无参数)构造函数,则这意味着根据设计该类必须使用 balance 进行初始化
值。
这意味着除非使用默认值(例如super(0)
)对其进行初始化,否则无法执行您要做的事情。
该错误是由于您在实际构造父类(super class)之前访问了父类(super class)的字段,这是您在子类中必须做的第一件事。
关于Java - 是否可以让子类构造函数只有 1 个参数,而不涉及调用 super()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40950839/