Unit 3 Cycle 1 Day 22: Polymorphism in Arrays
Share
Polymorphism in Arrays
Section 3.15 — Creating References
Key Concept
Polymorphism in arrays allows an array declared with a superclass type to hold objects of any subclass. Animal[] zoo = new Animal[3] can store Dog, Cat, and Animal objects. When iterating through the array and calling methods, dynamic dispatch ensures each object uses its own overridden version. The AP exam tests array processing where different elements respond differently to the same method call. The compile-time type of the array determines available methods, while each element's runtime type determines behavior.
Consider classes Dog and Cat that extend Animal, each overriding sound().
What is printed?
Answer: (B) Woof Meow Woof
The array holds Animal references, but the actual objects are Dog, Cat, Dog. Polymorphism: each sound() call uses the actual object's version. Output: Woof Meow Woof.
Why Not the Others?
(A) The Animal version returns "...", but it is overridden by Dog and Cat. Polymorphism uses the actual type.
(C) pets[1] is a Cat, so it returns "Meow", not "Woof".
(D) An Animal array can hold Dog and Cat objects (subclasses). This is valid polymorphism.
Common Mistake
Arrays of a parent type can hold any subclass objects. When calling methods, Java uses dynamic dispatch to run the actual object's version of the method.
AP Exam Tip
Polymorphic arrays are heavily tested. The declared type is the array element type (Animal), but each element can be a different subclass. Method calls use the actual object type.