How to Override Java Inheritance
- 1). Define the parent class in your Java application, as in the following sample code:
public class BankAccount {
private float balance;
public BankAccount(float initialBalance) {
balance = initialBalance;
}
public withdraw(float amount) {
balance -= amount;
}
} - 2). Define the subclass using Java's keyword "extends", as in the following sample code:
public class SavingsAccount extends BankAccount {
}
By default, SavingsAccount (a particular case of BankAccount) will inherit the attribute "balance" and the two methods from its parent class. - 3). Override a method by declaring it within the subclass with exactly the same signature as in the parent class, as in the following sample code:
public class SavingsAccount extends BankAccount {
private int transactionsThisMonth = 0;
public withdraw(float amount) {
if (transactionsThisMonth < 6) {
balance -= amount;
transactionsThisMonth++;
}
}
}
The new version of method "SavingsAccount.withdraw()" overrides the inherited method "BankAccount.withdraw()"; in this example, the reason is that savings accounts are subject to monthly limits in the number of allowable transactions. The constructor and the "balance" attribute are still unchanged, as inherited from the parent class.
Source...