Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 08 / Topic 7 of 12

Polymorphism

Polymorphism ("many shapes") means a single line of code — acc.monthlyFee() — runs a different method body depending on the real, run-time type of the object acc refers to, not the declared type of the variable. This is what makes a List<BankAccount> useful even when it secretly holds several different kinds of account: the calling code never needs an if to ask "what kind are you?" Think of handing a repair job to "whoever is on duty": the job ticket says "fix this", and which mechanic's exact technique runs depends on who shows up, not on what the ticket says.

Real-world example: a mixed list of accounts, each computing its own monthly fee.

static class BankAccount {
    protected final String accountNumber;
    protected double balance;
    BankAccount(String accountNumber, double balance) { this.accountNumber = accountNumber; this.balance = balance; }
    double monthlyFee() { return 0.0; }       // the default: no fee
    @Override public String toString() {
        return accountNumber + ": balance ₹" + balance + ", monthly fee ₹" + monthlyFee();
    }
}
static class SavingsAccount extends BankAccount {
    SavingsAccount(String accountNumber, double balance) { super(accountNumber, balance); }
    @Override double monthlyFee() { return 0.0; }        // savings: still free
}
static class CurrentAccount extends BankAccount {
    CurrentAccount(String accountNumber, double balance) { super(accountNumber, balance); }
    @Override double monthlyFee() { return 150.0; }      // current accounts carry a flat fee
}

static double totalMonthlyFees(List<BankAccount> accounts) {
    double total = 0.0;
    for (BankAccount acc : accounts) {
        total += acc.monthlyFee();             // which monthlyFee() runs depends on the real object, not the variable's type
    }
    return total;
}
SBIN0001234: balance ₹50000.0, monthly fee ₹0.0
HDFC0005678: balance ₹120000.0, monthly fee ₹150.0
ICIC0009999: balance ₹30000.0, monthly fee ₹150.0
total monthly fees across all accounts: ₹300.0

The loop variable acc is declared as BankAccount, but each actual object is a SavingsAccount or a CurrentAccount. acc.monthlyFee() always calls the overridden version that belongs to the object's real class — this run-time decision is called dynamic dispatch. Compare this with the overloading from section 2 (Wallet(String) versus Wallet(String, double)): overloading is decided at compile time by the arguments you pass; overriding is decided at run time by the object you are calling on. Both reuse the same method name, for entirely different reasons.

Full program: examples/Polymorphism.java.

Done here? The practice set for Part 8 — including the solutions — is on the part page.

Search the guide