Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
public class Main {
public static void main(String[] args) {
Animal a = new Cat();
Dog d = (Dog) a;
d.bark();
}
}
class Animal {}
class Cat extends Animal {}
class Dog extends Animal {
void bark() { System.out.println("Woof"); }
}A ClassCastException is thrown
- Expecting
Woof: a cast does not turn one object into another;(Dog) aonly checks that the object is aDog, and aCatfails the check. - Expecting a compile error: the compiler sees only the declared type
Animal, which may lead to aDog, so the mistake shows up only at run time.
- How would you check the object's type before casting it?
- Why does
(Dog) new Cat()not compile while(Dog) adoes?