throws子句在繼承當(dāng)中overrride時有什么規(guī)則?
throws子句在繼承當(dāng)中overrride時的規(guī)則
馬克-to-win:當(dāng)子類方法override父類方法時,throws子句不能引進(jìn)新的checked異常。換句話說:子類override 方法的throws子句checked異常不能比父類多。馬克-to-win:上面一條是死語法規(guī)定,這種規(guī)定,實際上都是源于checked異常這種最初的設(shè)計。
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
例:1.8.1-本章源碼
import java.io.IOException;
class Animal{
void call() throws IOException
{
System.out.println("Animal");
}
}
class Dog extends Animal{
void call() throws IOException
{
System.out.println("Dog");
}
}
public class Test {
public static void main(String args[]) throws IOException {
Dog d = new Dog();
d.call();
}
}
輸出結(jié)果:
Dog
馬克-to-win:為了讓讀者更加清楚一點,現(xiàn)在我們假象程序員在編Dog的時候就突發(fā)奇想想加一個SQLException,會發(fā)生什么?
例:1.8.2(有問題不能編譯)-本章源碼
import java.io.IOException;
import java.sql.SQLException;
class Animal{
void call() throws IOException
{
System.out.println("Animal");
}
}
class Dog extends Animal{
/*馬克-to-win:這里報錯說父類的throws得加上SQLException,Exception SQLException is not compatible with throws clause in Animal.call()*/
void call() throws IOException, SQLException
{
System.out.println("Dog");
}
}
public class Test {
public static void main(String args[]) throws IOException {
Dog d = new Dog();
d.call();
}
}