Below is the sample code
class Animal {
void makeNoise() {System.out.println("generic noise"); }
}
class Dog extends Animal {
void makeNoise() {System.out.println("bark"); }
void playDead() { System.out.println("roll over"); }
}
class DogTest {
public static void main(String [] args) {
Animal animal = new Animal();
Dog d = (Dog) animal;
d.makeNoise();
}
}
Above code compiles well but when i try to run it, i get
java.lang.ClassCastException
My assumption is it should print "generic noise" because at run time it should invoke actual Animal object makeNoise() method without giving any exception.
You can't cast an arbitrary Animal instance to a Dog instance, unless the instance you are casting is actually a Dog or a sub-class of Dog.
It would make more sense for the Animal class to be abstract, since an actual Animal that can be instantiated should be a specific Animal, such as Dog, Cat, etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With