Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class Animal {}
public class Dog extends Animal {
    public String fetch() { return "fetched"; }
}
// Usage:
Animal a = new Dog();
String result;
if (a instanceof Dog) {
    Dog d = (Dog) a;
    result = d.fetch();
} else {
    result = "no";
}
System.out.print(result);

What is printed?

  • A

    fetched

    check_circle
  • B

    Compile error: Animal has no fetch()

  • C

    ClassCastException at runtime

  • D

    no

Explanation

Since a is actually a Dog, the instanceof check passes, and the downcast (Dog) a succeeds. fetch() returns "fetched".

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

Related questions