AP Computer Science A · Topic 9.6
Polymorphism Practice
Part of Inheritance.
Practice questions
18
Sample questions
5 of 18 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public class A { public String name() { return "A"; } } public class B extends A { public String name() { return "B"; } } // Usage: A obj = new B(); System.out.print(obj.name());What is printed?
- A
AB
- Bcheck_circle
B
- C
Compile error
- D
A
Why
Method dispatch in Java is based on the runtime (actual) type of the object, not the declared type. obj refers to a B object, so B's name() is called, printing "B".
- A
Sample 2difficulty 2/5
public class Animal { public String sound() { return "generic"; } } public class Dog extends Animal { public String sound() { return "Woof"; } } Animal a = new Dog(); System.out.println(a.sound());What is printed?
- Acheck_circle
Woof
- B
generic
- C
Compile-time error
- D
Runtime error
Why
Java uses dynamic dispatch: even though <code>a</code> is declared as <code>Animal</code>, the actual object is a <code>Dog</code>, so <code>Dog.sound()</code> is invoked at runtime.
- A
Sample 3difficulty 3/5
public class Animal { public String sound() { return "?"; } } public class Dog extends Animal { public String sound() { return "woof"; } } public class Zoo { public static String hear(Animal a) { return a.sound(); } } // Usage: System.out.print(Zoo.hear(new Dog()));What is printed?
- A
Animal
- B
Compile error
- C
?
- Dcheck_circle
woof
Why
A method that takes Animal can accept any subclass. Dynamic dispatch invokes Dog's sound, returning "woof".
- A
Sample 4difficulty 3/5
ArrayList<Object> list = new ArrayList<Object>(); list.add("hello"); list.add(42); list.add(3.14); int count = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i) instanceof String) count++; } System.out.print(count);What is printed?
- A
2
- B
0
- C
3
- Dcheck_circle
1
Why
Only "hello" is a String. 42 autoboxes to Integer, 3.14 to Double. So instanceof String is true exactly once.
- A
Sample 5difficulty 3/5
import java.util.*; public class A { public String f() { return "A"; } } public class B extends A { public String f() { return "B"; } } List<A> list = new ArrayList<>(); list.add(new B()); A x = list.get(0); System.out.println(x.f());What is printed?
- Acheck_circle
B
- B
AB
- C
Compile-time error
- D
A
Why
Stored as B, accessed via A reference; dynamic dispatch picks B.f.
- A