public class Animal {}
public class Dog extends Animal {
public void bark() { System.out.print("Woof"); }
}
Animal a = new Animal();
if (a instanceof Dog) {
((Dog) a).bark();
} else {
System.out.print("not a dog");
}What is printed?
- A
ClassCastException
- B
Compile-time error
- Ccheck_circle
not a dog
- D
Woof
Explanation
The instanceof check prevents the unsafe cast. a is just an Animal, not a Dog.