簡體   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());
    }
}

當我編譯此代碼時,它在第23行顯示ClassCastException。我無法理解問題所在。 救命 !!

當對象強制轉換為該對象不是其實例的數據類型時,JVM會引發ClassCastException。

例如

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

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

為了避免ClassCastException,您可以使用instanceof

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

希望您能理解。 謝謝。

問題是您正在嘗試將類型更具體的類轉換為類型更具體的類。 更簡單地說,貓或狗可以是動物,因此您可以將狗和貓聲明為動物,如下所示:

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

但是您不能將動物稱為貓或狗,因此以下聲明無效

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

這樣做的原因很簡單,這是因為在這種情況下,更具體的類(例如貓或狗)可能具有更多的方法/實例變量,而在更一般的情況下不存在。 動物應該具有所有動物共有的屬性和方法,但貓或狗可能會做一些並非所有動物都能使用的事情。

在堅果殼中,您不能使用子類引用來引用超類對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM