這裏是我的抽象類: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