AP Computer Science A · Topic 9.1
Creating Superclasses and Subclasses Practice
Part of Inheritance.
Practice questions
29
Sample questions
5 of 29 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
<code>class Dog extends Animal { }</code> declares
- A
Dog as a parent of Animal
- Bcheck_circle
Dog as a subclass of Animal
- C
Animal containing a Dog
- D
Compile error
Why
<code>extends</code> indicates inheritance: Dog inherits from Animal.
- A
Sample 2difficulty 2/5
public class Parent { protected int x = 5; } public class Child extends Parent { public int doubleX() { return x * 2; } } // Usage: Child c = new Child(); System.out.print(c.doubleX());What is printed?
- A
0
- B
Compile error: x is private
- C
5
- Dcheck_circle
10
Why
x is protected, so Child can access it directly. x = 5, so doubleX() returns 10.
- A
Sample 3difficulty 2/5
public abstract class Animal { public abstract String sound(); } // Usage: Animal a = new Animal();What occurs?
- A
Compiles fine
- B
Compiles and creates an Animal with null sound
- Ccheck_circle
Compile error: Animal is abstract; cannot be instantiated
- D
Runtime error when sound() is called
Why
Abstract classes cannot be directly instantiated with new. The compiler reports an error.
- A
Sample 4difficulty 2/5
public class A { public int doubleIt(int n) { return n * 2; } } public class B extends A { } System.out.println(new B().doubleIt(7));What is printed?
- A
Compile-time error
- B
7
- Ccheck_circle
14
- D
0
Why
B inherits doubleIt from A.
- A
Sample 5difficulty 2/5
public class Engine { } public class Car { private Engine e; public Car() { e = new Engine(); } }What relationship does Car have with Engine?
- Acheck_circle
has-a (composition)
- B
is-a (inheritance)
- C
neither
- D
is-a abstract
Why
Car CONTAINS an Engine as a field — has-a (composition). is-a would require <code>Car extends Engine</code>.
- A