<aside> 🔀

L3.2 — Polymorphism covers method overriding (replacing superclass methods with subclass-specific versions), dynamic binding (Java resolving the most specific method at runtime), how substitution + overriding + dynamic binding combine to give polymorphism, the toString() method, designing class hierarchies for polymorphism (the Broker example), overloading vs overriding, and the this and super keywords for accessing properties and methods.

</aside>

📋 At a Glance


1. Overriding Methods

What is Overriding?

Overriding means a subclass provides its own version of a method that is already defined in its superclass. The subclass version replaces the superclass version for objects of that subclass type.

The Animal Example

public class Animal {
    public void sleep() { System.out.println("zzz"); }
    public void roam()  { System.out.println("wanders about"); }
    public void eat()   { System.out.println("eats something"); }
}
public class Dog extends Animal {
    public void roam() { System.out.println("roams in packs"); }
    public void eat()  { System.out.println("eats meat"); }
    // sleep() is inherited from Animal — not overridden
}

public class Cat extends Animal {
    public void roam() { System.out.println("roams independently"); }
    public void eat()  { System.out.println("eats meat"); }
}

public class Elephant extends Animal {
    public void eat()  { System.out.println("eats grass"); }
    // sleep() and roam() are inherited from Animal
}