2013-03-07 48 views
0

我有一個基類和一個派生類。我寫的代碼是如何處理java中的ClassCastException

class Base { 
    ... 
} 

class derived extends base { 
} 

class Main { 
    public static void main(String[] args){ 
     derived d = (derived) new Base(); //throws a ClassCastException 
    } 
} 

這是如何處理的?我想在不使用super關鍵字的情況下調用基類方法。

+0

'Base'不是'Derived'所以它不能被轉換爲'Derived' – Esailija 2013-03-07 11:22:21

+0

......而'Derived'是'Base'所以它可以被轉換成'Base';) – sp00m 2013-03-07 11:25:47

回答

1

基類是一個超類,派生類是子類。你不能在子類的引用中捕獲超類的對象。

Base b = new Derived(); 

上述指令將工作,但

但以下將無法正常工作。

Derived d = new Base(); 
0

你可以在不使用super的情況下調用超類的方法。

基地:

public class Base { 

    public void print() { 
     System.out.println("Base"); 
    } 

} 

派生:

public class Derived extends Base {...} 

主要:

public static void main(String[] args) { 
    Derived d = new Derived(); 
    d.print(); 
} 

打印出:

Base

0

實際上'基地'不是'派生',所以鑄造是不可能的。

,將在以下情況下

底座B =新的派生() 衍生d =(導出)B具有成爲可能;

0

向下轉換在java中是不可能的。這是唯一可能在基類存儲派生類的參考

Base b = new Derived() 

// Check is required. It may lead to ClassCastException otherwise 
if (b instancof D)  
    Derived d = (Derived) b;