AP CSA Inheritance and Polymorphism 2 — Questions and Answers
Question 1: What is dynamic dispatch (dynamic method lookup) in Java?
- The JVM determines which overridden method to call based on the actual runtime type of the object (Correct answer)
- The compiler selects the method at compile time based on the declared type
- A method that dispatches multiple threads
- A way to call methods using reflection
Correct answer: The JVM determines which overridden method to call based on the actual runtime type of the object
Dynamic dispatch means the JVM uses the actual object type at runtime (not the declared reference type) to decide which overridden method to invoke.
Question 2: If class Dog extends Animal and both have a `speak()` method, what does `Animal a = new Dog(); a.speak();` call?
- Dog's speak() method (Correct answer)
- Animal's speak() method
- Both methods in sequence
- A compile error
Correct answer: Dog's speak() method
Due to dynamic dispatch, the JVM looks at the actual object type (Dog) at runtime and calls Dog's speak() method, not Animal's.
Question 3: What does it mean for a class to be `abstract`?
- It cannot be instantiated and may contain abstract methods (Correct answer)
- It has no fields
- It cannot have any methods
- It is the superclass of all classes
Correct answer: It cannot be instantiated and may contain abstract methods
An abstract class cannot be instantiated directly and can declare abstract methods that subclasses must implement.
Question 4: What must a concrete (non-abstract) subclass do with abstract methods it inherits?
- Implement (override) all of them (Correct answer)
- Ignore them
- Declare them abstract again
- Delete them
Correct answer: Implement (override) all of them
A concrete subclass must provide implementations for all abstract methods inherited from its abstract superclass, or itself be declared abstract.
Question 5: Can a subclass inherit from multiple superclasses in Java?
- No, Java only supports single inheritance for classes (Correct answer)
- Yes, using the extends keyword multiple times
- Yes, using the implements keyword for classes
- No, and interfaces also don't support multiple inheritance
Correct answer: No, Java only supports single inheritance for classes
Java supports single class inheritance only — a class can extend only one superclass, though it can implement multiple interfaces.
Question 6: What is a common use of the `instanceof` operator in polymorphism?
- To check the actual runtime type of an object before a downcast (Correct answer)
- To check if two objects are equal
- To create a new object of a given type
- To call a superclass method
Correct answer: To check the actual runtime type of an object before a downcast
`instanceof` tests whether an object is an instance of a specific class, commonly used before casting a superclass reference to a subclass type.
What is dynamic dispatch (dynamic method lookup) in Java?