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?
- Acheck_circle
fetched
- 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".