AP Computer Science A · Topic 9.5
Creating References Using Inheritance Hierarchies Practice
Part of Inheritance.
Practice questions
28
Sample questions
5 of 28 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public class Animal {} public class Dog extends Animal {} public class Cat extends Animal {} // Usage: Animal a = new Dog(); System.out.print(a instanceof Dog); System.out.print(" "); System.out.print(a instanceof Animal); System.out.print(" "); System.out.print(a instanceof Cat);What is printed?
- A
false true false
- B
true true true
- C
true false false
- Dcheck_circle
true true false
Why
a refers to a Dog. instanceof Dog is true; instanceof Animal is true (Dog is-a Animal); instanceof Cat is false (Dog is not a Cat).
- A
Sample 2difficulty 2/5
public abstract class Vehicle { public abstract int wheels(); } public class Bike extends Vehicle { public int wheels() { return 2; } } // Usage: Vehicle v; v = new Bike(); System.out.print(v.wheels());What is printed?
- A
Runtime error
- B
Compile error: cannot declare Vehicle reference
- C
0
- Dcheck_circle
2
Why
Abstract classes can be used as REFERENCE types even though they cannot be instantiated. v refers to a Bike, and dispatch returns 2.
- A
Sample 3difficulty 2/5
public class Animal {} public class Dog extends Animal { public void bark() { System.out.println("Woof"); } } Animal a = new Dog(); a.bark();What happens?
- Acheck_circle
Compile-time error: bark not in Animal
- B
Prints Woof
- C
Runtime error
- D
Prints nothing
Why
Method calls are checked against the declared (compile-time) type. Animal has no <code>bark</code>, so this fails to compile even though the object is a Dog.
- A
Sample 4difficulty 2/5
public class Animal {} public class Cat extends Animal {} Animal a = new Cat(); System.out.println(a instanceof Cat); System.out.println(a instanceof Animal);What is printed?
- Acheck_circle
true true
- B
true false
- C
false false
- D
false true
Why
The actual object is a Cat, which is also an Animal. Both checks return true.
- A
Sample 5difficulty 3/5
public class Item {} public class Book extends Item { public String title() { return "Book"; } } public class Toy extends Item { public String name() { return "Toy"; } } public static String describe(Item i) { if (i instanceof Book) return ((Book) i).title(); if (i instanceof Toy) return ((Toy) i).name(); return "?"; } // Usage: System.out.print(describe(new Toy()));What is printed?
- A
Book
- B
?
- C
ClassCastException
- Dcheck_circle
Toy
Why
instanceof Book is false; instanceof Toy is true; the cast succeeds and name() returns "Toy".
- A