Physco111
Physco111

Reputation: 227

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

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.

Upvotes: 3

Views: 505

Answers (1)

Jack
Jack

Reputation: 133567

If parent class doesn't have a default (no arguments) constructor then this means that by design the class must be initialized with a balance value.

This implies that there is no way to do what you are tying to do, unless initializing it with a default value (eg super(0)).

The error is given by the fact that you are accessing a field of the super class before actually constructing it, which is the first thing you must do in a subclass.

Upvotes: 2

Related Questions