Next: Conversions. Up: Subclasses. Previous: Inheritance.


Overriding methods

Textbook: Section 11.3

Sometimes the method inherited from the parent class isn't exactly right for the subclass. For example, say we want a SavingsAccount subclass, InvestmentAccount, where the bank takes off a 3% commission on each deposit (which the customer accepts because they want the higher interest rate). In this case, we want to change the behavior of the account when somebody calls deposit(). We can do this by defining a new version of deposit() in the subclass. This overrides Account's deposit() method.

public class InvestmentAccount extends SavingsAccount {
    public static final double INTEREST = 0.05;
    public static final double COMMISSION = 0.03;

    public InvestmentAccount() {
        super(INTEREST);
    }

    public void deposit(double amount) {
        super.deposit(amount * (1.0 - COMMISSION));
    }
}
In our definition of the deposit() instance method, you can see something new: we've called deposit() on super - this indicates that the computer should call SavingsAccount's deposit() method - but you can see that the argument we pass it is only 97% of the argument passed into InvestmentAccount's deposit() method.

When a subclass overrides a method, the effect even applies to times the method is called in the parent class. For example, InvestmentAccount inherited from SavingsAccount the addInterest() method, defined as follows in SavingsAccount.

    public void addInterest() {
        deposit(getBalance() * (1.0 + interest));
    }
This method calls the deposit() method. Say I call addInterest() on an InvestmentAccount. You might think that this would call Account's deposit() method. It does not. It calls InvestmentAccount's deposit() method (which itself calls Account's deposit - after taking off the commission). The overall result is that the bank culls a commission even on the interest!

This behavior is not accidental - in fact, Java goes to great lengths to accomplish it. It's quite useful. In fact, often a class will define a method simply so that subclasses will override it. For example, the DrawableFrame class defines a keyTyped() method that gets called every time the user types a key. The method defined there does nothing. But a subclass can override the method to define new behavior.

You'll be using this in your next Breakout lab, as you'll want a user's keypress to alter the direction of the paddle. You'll do something like the following.

public class BreakoutFrame extends DrawableFrame {
    private Paddle paddle;
    public void keyTyped(char c) {
        // move paddle based on key typed
    }
}
Your own program will never actually call the keyTyped() method. But it's still useful to have, as the code within DrawableFrame calls it each time the user types a key.


Next: Conversions. Up: Subclasses. Previous: Inheritance.