简体   繁体   中英

Java polymorphism casting - runtime error ClassCastException

I have this code here:

public class code {

    public static void main(String args[]){

        Animal ani1 = new Animal();
        Animal ani2 = new Dog();

        Dog d1 = (Dog)ani1; //runtime error ClassCastException
        Dog d2 = (Dog)ani2;
    }
}

class Animal {
    public String name = "animal";
    public void talk(){
        System.out.println("Animal");
    }
}

class Dog extends Animal {
    public String name = "dog";
    public void talk(){
        System.out.println("Dog");
    }
}

I am not understanding why a runtime error is occurring and downcasting in general. There are 2 objects being created, an Animal object and a Dog object. Each is referenced to by a variable of type Animal .

I think Java will not assign d1 an object of type Animal because d1 was declared as type Dog . But what is confusing me is that both ani1 and ani2 are type Animal , and should be able to be downcasted to Dog right? The only difference is that one is referencing an Animal object and the other a Dog object.

Does Java know that ani1 is referencing an Animal object and will not allow d1 to be assigned a variable that references an Animal object?

What VGR said was right, you cannot change what something is. Casting is only here to help our code during compilation recognize what it is.

Consider the ff example:

Animal ani1 = new Cat();
Animal ani2 = new Dog();

Dog dog1 = (Dog) ani1; // will produce a runtime error
Dog dog2 = (Dog) ani2;

Just like the given example, you cannot simple change Cat to Dog by simply casting. Dog will always be an Animal but an Animal can't always be a Dog .

The comment by VGR is correct, but let me elaborate for your specific situation. A Dog is an Animal, but an Animal is not necessarily a Dog. You could create Dog objects and pass them around as Animal objects, but not the other way around. A common way to handle this would be the following:

public static void main(String args[]) {        
    Dog dog = new Dog();
    makeMeTalk(dog);
}

public static void makeMeTalk(Animal animal) {
    animal.talk();
}

The output of this would be: Dog .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM