Unit 3 Cycle 2 Day 3: Polymorphism: Compile vs Runtime Type

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

Polymorphism: Compile vs Runtime Type

Section 3.15 — Creating References

Key Concept

The compile-time type (declared type) determines what methods can be called, while the runtime type (actual object type) determines which version of a method executes. For Animal a = new Dog(), calling a.speak() is valid only if Animal defines speak(), but the Dog version runs. Calling a.fetch() causes a compile error even if Dog defines it, because Animal does not. This two-type system is the most frequently tested polymorphism concept on the AP exam.

Consider the following hierarchy.

public class Fruit { public String taste() { return "sweet"; } } public class Lemon extends Fruit { public String taste() { return "sour"; } public String color() { return "yellow"; } }

Which of the following causes a compile-time error?

Answer: (C) Fruit f = new Lemon(); f.color();

The reference type is Fruit, which does not define color(). Even though the actual object is a Lemon (which has color()), the compiler only sees Fruit's methods.

Why Not the Others?

(A) taste() is defined in Fruit, so the compiler allows it. At runtime, Lemon's version runs.

(B) l is declared as Lemon, so all Lemon methods (including color()) are visible.

(D) taste() is inherited from Fruit and available on Lemon objects.

Common Mistake

The compiler checks the declared (compile-time) type to see if a method exists. The runtime type determines which version runs. Calling a subclass-only method through a parent reference fails at compile time.

AP Exam Tip

Compile-time type = what you CAN call. Runtime type = which VERSION runs. A Fruit reference cannot call Lemon-specific methods without a cast.

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.