3

Here is my abstract class:

public abstract class BankAccount{
  protected long balance;

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

  ... more stuff
}

I have the following subclass (also an extra subclass SavingsAccount, they both have their own independent balance, but's that's irrelevant):

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
}

As you can see from above, I want a constructor that just sets the overdraft, but I still need to call super at the start of every constructor, so I'm just passing in, whatever the balance currently is, can I even do that? Or do I need a balance variable in my CurrentAccount subclass aswell?

When compiling java is giving me this:

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

Any help would be appreciated.

4

1 回答 1

2

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

这意味着没有办法做你想做的事情,除非用默认值(例如super(0))初始化它。

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

于 2016-12-03T18:05:42.237 回答