简体   繁体   English

在Java中强制转换类别时发生类别转换例外

[英]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. 当我编译此代码时,它在第23行显示ClassCastException。我无法理解问题所在。 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. 当对象强制转换为该对象不是其实例的数据类型时,JVM会引发ClassCastException。

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 为了避免ClassCastException,您可以使用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. 在坚果壳中,您不能使用子类引用来引用超类对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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