AP CSA Inheritance and Polymorphism 3 — Questions and Answers
Question 1: What is a 'has-a' relationship in OOP (as opposed to 'is-a')?
- Composition — one class contains a reference to another class (Correct answer)
- Inheritance — one class extends another
- Overriding — one class replaces a method
- Abstraction — hiding implementation details
Correct answer: Composition — one class contains a reference to another class
A 'has-a' relationship is composition: a class holds a reference to another class as a field, rather than inheriting from it.
Question 2: What does the `final` keyword do when applied to a method in Java?
- Prevents the method from being overridden in subclasses (Correct answer)
- Makes the method run only once
- Makes the method static
- Prevents the method from being called externally
Correct answer: Prevents the method from being overridden in subclasses
A `final` method cannot be overridden by any subclass, locking its implementation for the entire inheritance hierarchy.
Question 3: Which of the following correctly performs a downcast from Animal to Dog?
- Dog d = (Dog) a; (Correct answer)
- Dog d = a;
- Dog d = new Dog(a);
- Dog d = a.toDog();
Correct answer: Dog d = (Dog) a;
A downcast requires an explicit cast operator `(Dog)` to convert a superclass reference to a subclass reference.
Question 4: What is the role of an interface in Java's type system for AP CSA purposes?
- It defines a contract of methods that implementing classes must provide (Correct answer)
- It is a class that cannot be instantiated
- It provides a default implementation for all methods
- It replaces the need for inheritance
Correct answer: It defines a contract of methods that implementing classes must provide
A Java interface specifies a set of method signatures that any implementing class must define, establishing a contract without providing implementations.
Question 5: If a subclass constructor does not explicitly call `super()`, what happens in Java?
- Java automatically inserts a call to the no-argument superclass constructor (Correct answer)
- A compile error occurs
- The superclass fields are left uninitialized
- The superclass constructor is never called
Correct answer: Java automatically inserts a call to the no-argument superclass constructor
If no explicit super() call is made, Java implicitly calls the superclass's no-argument constructor as the first action of the subclass constructor.
Question 6: What is the term for when a superclass method calls an overridden method that runs the subclass version?
- Polymorphic dispatch (Correct answer)
- Static binding
- Method hiding
- Encapsulation
Correct answer: Polymorphic dispatch
Polymorphic dispatch (dynamic binding) means that even when called from within a superclass method, the overridden subclass version runs because the object's actual type governs the call.
What is a 'has-a' relationship in OOP (as opposed to 'is-a')?