Unit 3 Cycle 1 Day 22: Polymorphism in Arrays

Unit 3 Foundation (Cycle 1) Day 22 of 28 Foundation

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().

Animal[] pets = new Animal[3]; pets[0] = new Dog(); // sound() returns "Woof" pets[1] = new Cat(); // sound() returns "Meow" pets[2] = new Dog(); // sound() returns "Woof" String result = ""; for (int i = 0; i < pets.length; i++) { result += pets[i].sound() + " "; } System.out.println(result);

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.

Review this topic: Section 3.15 — Creating References • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.