Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 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

  • D

    Toy

    check_circle

Explanation

instanceof Book is false; instanceof Toy is true; the cast succeeds and name() returns "Toy".

Want 10 more like this — adaptive to your weak spots?

Related questions