Java - 是否可以让子类构造函数只有 1 个参数,而不涉及调用 super()?

Java - Is it possible to have a subclass constructor only 1 parameter, that doesn't involve calling super()?

这是我的摘要class:

public abstract class BankAccount{
  protected long balance;

  public BankAccount(long balance){ \<--Abstract class constructor
    this.balance = balance;
  }

  ... more stuff
}

我有以下subclass(还有一个额外的subclass 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 subclass 中也需要一个余额变量?

编译时 java 给我这个:

CurrentAccount.java:41: error: cannot reference balance before supertype constructor has been called
    super(balance);
          ^
1 error

如有任何帮助,我们将不胜感激。

如果父 class 没有默认(无参数)构造函数,那么这意味着 设计 class 必须用 balance 值初始化。

这意味着除非用默认值初始化它(例如 super(0)),否则无法执行您想要执行的操作。

错误是由于您在实际构造它之前访问了超级 class 的字段,这是您必须在子 class 中做的第一件事。