2012.11.18補充:除非新的exception為RuntimeException或其子類別。
例1:
class A{
A length(){return this;}
}
class Test1 extends A{
Test1 length()throws NullPointerException{ return this;}
public static void main(String[] args){
System.out.println(new Test1().length());
}
}
------------
Test1@57f0dc
說明:
Test1 length()throws NullPointerException{ return this;}:劃線為合法,因為可宣告回傳型別為父函式的子型別;又因為父函式未宣告exception,所以表示父函式可能丟出任何exception,而NullPointerException為exception的子類別,符合覆寫規則。
證明:
class A{A length()throws NullPointerException{return this;}}
class Test1 extends A{
Test1 length()throws Exception {return this;}
public static void main(String[] args){
System.out.println(new Test1().length());
}
}
---------------
Test1.java:4: length() in Test1 cannot override length() in A; overridden method does not throw java.lang.Exception
Test1 length()throws Exception {return this;}
^
例2:
class MyException extends Exception{}
class A{A length(){return this;}}
class Test1 extends A{
Test1 length()throws MyException {return this;}
public static void main(String[] args){
System.out.println(new Test1().length());
}
}
----------------
Test1.java:4: length() in Test1 cannot override length() in A; overridden method does not throw MyException
Test1 length()throws MyException {return this;}
^
不能丟新的exception。不過明明MyException就有繼承Exception啊,為何還是無法通過編譯呢?
2012.11.18更新
上面觀念錯了,在此重新𨤳淸:
一個覆寫的函式的確不能丟出範圍比父函式要大的例外。
只有一種可以:RuntimeException(包含其子類別)可以由子函式丟出。因為RuntimeException為非可控式例外(unchecked exception)不用去處理;基本上無視它就是了。
所以上面例1的Test1 length()throws NullPointerException{ return this;},NullPointerException為RuntimeException的子類別,所以子函式雖然有宣告,但編譯器無視它,當做沒這回事,當然就能順利編譯。但例2的Test1 length()throws MyException {return this;},MyException為Exception的子類別,非屬於RuntimeException,所以編譯無法通過。
沒有留言:
張貼留言