Thompson Rivers University
Inheritance Cheat Sheet
Final Exam Prep - SM 2025What inheritance means
A subclass extends a superclass to reuse fields and methods.
It forms an is a relationship.
SavingsAccount is a BankAccount.Java supports single inheritance for classes and multiple inheritance for interfaces.
Extending a class
class BankAccount {
protected String name;
protected int accountNumber;
protected double balance;
public BankAccount(String name, int number, double balance) {
this.name = name;
this.accountNumber = number;
this.balance = balance;
}
public void deposit(double amount) { this.balance += amount; }
public void withdraw(double amount) { this.balance -= amount; }
public String getAccountType() { return "Base"; }
@Override
public String toString() {
return name + " #" + accountNumber + " $" + balance;
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(String name, int number, double balance, double rate) {
super(name, number, balance); // super must be the first statement
this.interestRate = rate;
}
public void applyBonus() {
this.balance += 100.0; // can access because parent used protected
}
@Override
public String getAccountType() {
return "Savings";
}
@Override
public String toString() {
return super.toString() + " " + interestRate + "%";
}
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 54 more lessons in Thompson Rivers University.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.