Unit 3 Cycle 2 Day 15: Polymorphic Array Processing

Unit 3 Advanced (Cycle 2) Day 15 of 28 Advanced

Polymorphic Array Processing

Section 3.15 — Creating References

Key Concept

Processing an array of polymorphic objects requires iterating through the array and calling methods on each element. Since the array type is the superclass, only superclass methods can be called directly. But overridden methods execute the subclass version for each element based on its runtime type. A common AP exam pattern: iterate through an Animal[] and call makeSound() — each element produces different output based on whether it is a Dog, Cat, or plain Animal.

Consider classes where Circle and Square extend Shape, each overriding area().

Shape[] shapes = {new Circle(5), new Square(4)}; // Circle area = pi * r * r (78.54) // Square area = side * side (16) double total = 0; for (Shape s : shapes) { total += s.area(); } System.out.println(total > 50);

What is printed?

Answer: (A) true

Circle area: 3.14159*25 = ~78.54. Square area: 16. Total: ~94.54. 94.54 > 50 is true.

Why Not the Others?

(B) 78.54 + 16 = 94.54, which is greater than 50.

(C) A Shape array can hold Circle and Square objects. area() is defined in Shape.

(D) Polymorphism works correctly at runtime, calling each object's area() method.

Common Mistake

Polymorphic arrays allow processing different object types uniformly. Each s.area() call dispatches to the correct override based on the actual object type.

AP Exam Tip

Processing arrays of parent-type references is a fundamental polymorphism pattern. The enhanced for loop works with polymorphic arrays.

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.