简体   繁体   中英

Class cast exception while casting a class in java

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"; 
    }
}
class jk{
    public static void main(String args[]){ 
        Animal animal = new Dog();
        Cat cat = (Cat)animal;//line 23
        System.out.println(cat.noise());
    }
}

when i compile this code it shows ClassCastException at line 23. I am not able to understand what the problem is. HELP !!

A ClassCastException is thrown by the JVM when an object is cast to a data type that the object is not an instance of.

For example

//Compile Error
Integer x = new Integer(10);
String y = (String) x;

//OK
Object x = new Integer(10);
String y = (String) x;

To Avoid ClassCastException you can use instanceof

Object x = new Integer(10);
 if(x instanceof String)
 {
 String y = (String) x;
 }

I hope you will understnad. Thank you.

The problem is you are trying to type cast a more specific class to a less specific one. More simply, A cat or A dog can be an animal so you can declare dogs and cats as animals as follows:

Animal cat = new Cat();
Animal dog = new Dog();

however you can not refer to an animal as a cat or a dog so the following declarations are invalid

Cat cat = new Animal();
Dog dog = new Animal();
Cat cat = new Dog();
Dog dog = new Cat();

The reason for that is very simple and that's because a more specific class in this case like the cat or dog might have more methods/instance variables that are not present in the more general case. Animal should have the attributes and methods common to all animals but a cat or a dog might do something that's not available to all animals.

In a nut shell you cannot refer to super class object with a subclass reference.

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