0

I have the following Account class which is the super class of CurrentAccount. I am however having issues when I create an instance of each class. The currentAccount should take away 6 as a charge if the balance is below 100 but its taking away 3. I'm obviously missing a deceleration somewhere.

public class Account {

    private String name;
    private double balance;
    public double initDeposit;
    public double threshold = 100.00;
    public final double fee = 3.00;

    public Account(String name, double initDeposit) {
        this.balance = initDeposit;
        this.name = name;
    }

    public void deposit(double amount) {
        setBalance(amount);
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double amount) {
        balance += amount;
    }

    public void withdraw(double amount) {
        if (getBalance() < 100 && getBalance() >= -50) {
            balance = balance - amount - fee;
        } else {
            balance = balance - amount;
        }
    }

    public String toString() {
        String s = "Name: " + name + "\n" + "Balance: " + balance;
        return s;
    }
}

public class CurrentAccount extends Account {

    private String name;
    private double balance;
    public double initDeposit;
    public double threshold = 100.00;
    public final double fee = 6.00;

    public CurrentAccount(String name, double initDeposit) {
        super(name, initDeposit);
    }
}
3
  • what do you mean by "taking away 6" and "taking away 3"? Commented Feb 10, 2014 at 20:08
  • 3
    Your seem to be trying to overide instance variables but are in fact shadowing them. You need to pass variables you want into the superclass constructor rather than redeclare them. Commented Feb 10, 2014 at 20:09
  • What happens if the balance is less than -50 ? Commented Feb 10, 2014 at 20:10

1 Answer 1

4

In Java, instance variables do not replace or override the same named variable in a superclass. If you declare a same-named variable in a subclass, now you have two variables, not one. Just because you declared another fee in CurrentAccount doesn't mean the code in Account will use the fee in CurrentAccount -- it can't.

To apply the different behavior you need, declare a method called getFee() in Account returning a double that can be overridden in CurrentAccount to change the behavior.

In Account:

public double getFee() { return 3.00; }

In CurrentAccount:

@Override
public double getFee() { return 6.00; }

Then call getFee() whenever you need to reference the fee, instead of referring to fee.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.