Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification in reference variable downcasting in java

Tags:

java

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.

like image 397
amol saxena Avatar asked May 09 '26 22:05

amol saxena


1 Answers

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...

like image 154
Eran Avatar answered May 11 '26 14:05

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!