Unit 3 Cycle 2 Day 15: Polymorphic Array Processing
Share
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().
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.