AP CSA Inheritance and Polymorphism 1 — Questions and Answers
Question 1: What keyword does a subclass use to inherit from a superclass in Java?
- extends (Correct answer)
- implements
- inherits
- super
Correct answer: extends
In Java, a subclass uses the `extends` keyword to inherit fields and methods from its superclass.
Question 2: What does it mean to override a method in Java?
- A subclass provides its own implementation of a method defined in the superclass (Correct answer)
- A method calls itself recursively
- A class defines two methods with the same name
- A method is declared but not implemented
Correct answer: A subclass provides its own implementation of a method defined in the superclass
Method overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass.
Question 3: What keyword is used to call the superclass constructor from a subclass constructor?
- super() (Correct answer)
- this()
- parent()
- base()
Correct answer: super()
The `super()` call in a subclass constructor explicitly invokes the superclass constructor to initialize inherited fields.
Question 4: Which OOP principle allows a subclass object to be used wherever a superclass reference is expected?
- Polymorphism (Correct answer)
- Encapsulation
- Abstraction
- Overloading
Correct answer: Polymorphism
Polymorphism allows a subclass instance to be assigned to a superclass reference variable, enabling flexible and interchangeable use.
Question 5: What is the difference between method overriding and method overloading?
- Overriding redefines a superclass method; overloading defines multiple methods with the same name but different parameters (Correct answer)
- Overriding uses different parameter lists; overloading uses the same parameters
- They are the same thing
- Overloading only works in subclasses
Correct answer: Overriding redefines a superclass method; overloading defines multiple methods with the same name but different parameters
Overriding replaces a superclass method in a subclass with the same signature, while overloading creates multiple methods with the same name but different parameters in the same class.
Question 6: What is the purpose of the `@Override` annotation in Java?
- It tells the compiler to verify the method actually overrides a superclass method (Correct answer)
- It makes the method run faster
- It prevents the method from being overridden further
- It marks the method as abstract
Correct answer: It tells the compiler to verify the method actually overrides a superclass method
`@Override` is a compile-time check that causes a compile error if the annotated method doesn't actually override a superclass method.
What keyword does a subclass use to inherit from a superclass in Java?