Polymorphism and Dynamic Dispatch

Part of: Inheritance

One Type, Many Forms Polymorphism means "many forms." In Java, a superclass reference can point to any subclass object. When you call an overridden method through that reference, Java runs the subclass's version. The actual object decides which method runs, not the reference type. Superclass References Even though a is declared as Animal, the object is really a Dog, so Dog's overridden speak() runs. This selection-at-runtime is called dynamic dispatch (or late binding). Why This Matters You can store mixed subclasses in one array and treat them uniformly: Each element runs its own speak(). You write the loop once , and it works for every current and future subclass. Adding a new Bird subclass requires no change to this loop. The Rules of Dispatch - The declared (reference) type determines which methods you are allowed to call. - The actual (object) type determines which overridden version runs . So Animal a = new Dog(); lets you call only methods declared in Animal, but for overridden methods it runs Dog's code. A Subtle Point If you call a method that exists only in Dog (like fetch()) through an Animal reference, it will not compile , because the compiler checks the declared type.

Challenge: Zoo Sounds