What is the result?

Given:

class Animal {
public String noise() {
return “peep”;
}
}

class Dog extends Animal {
public String noise() {
return “bark”;
}
}

class Cat extends Animal {
public String noise() {
return “meow”;
}
}

30. Animal animal = new Dog();
31. Cat cat = (Cat)animal;
32. System.out.println(cat.noise());

What is the result?

Given:

class Animal {
public String noise() {
return “peep”;
}
}

class Dog extends Animal {
public String noise() {
return “bark”;
}
}

class Cat extends Animal {
public String noise() {
return “meow”;
}
}

30. Animal animal = new Dog();
31. Cat cat = (Cat)animal;
32. System.out.println(cat.noise());

What is the result?

A.
peep

B.
bark

C.
meow

D.
Compilation fails.

E.
An exception is thrown at runtime.

Explanation:
Exception in thread “main” java.lang.ClassCastException: Dog cannot be cast to Cat
at ClassTest.main(Main.java:31)



Leave a Reply 1

Your email address will not be published. Required fields are marked *