这里是我的抽象类:Java - 是否有可能有一个子类的构造函数只有1参数,这不涉及调用super()?
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
任何帮助,将不胜感激。
如果我创建了一个无参数构造函数,它不应该做些什么吗?如果我让它做一些无用的事情,比如将一个无意义的变量设置为0,那么这会不会是糟糕的编程? – Physco111
@ Physco111:这都是设计问题。在没有指定初始余额(默认为0)的情况下创建“BankAccount”是否有意义?如果答案是肯定的,那么你可以提供一个无参数的构造函数,它的初始化为0. – Jack
好的,谢谢你,我会说你的答案对我来说意义最大。 – Physco111