public class A { public void m() throws AException {}; }public class B extends A{ public void m() throws AException, BException {}; }public class Test { public static void main(Sting[] args) { A obj = new B(); try { obj.m(); //父类引用,m方法只抛出了AException,但实际调用的是B类的m方法,会抛出BException,但这里就捕获不到了 } catch (AException) { } } }
他的意思应该是说checked Exception. :)
你这个代码跟老师上课时讲的是差不多的,也是说父类引用子类的方法会出问题。 A obj = new B();这一句含义到底该怎么理解它呢?
[code=Java]class AAA{
public void setT() throws NumberFormatException{
}
}class BBB extends AAA{
public void setT() throws NumberFormatException, TypeNotPresentException{
}
}code]
class AAA{
public void setT() throws NumberFormatException{ }
} class BBB extends AAA{
public void setT() throws NumberFormatException, TypeNotPresentException{ }
}
Parent p = child;
try {
p.methodA();
} catch(ExceptionFromParent e) {
//执行方法异常
}
但是,实际上methodA还可能抛出ExceptionFromChild,
这样外部调用程序就无法写出当方法出现异常时候的处理了。
void xxx() throws Exception ---> void xxx() throws IOException / void xxx();这样,其他调用者调用的时候,只要以访问父类/接口方法的方式,就能正确调用子类/实现类的方法。也就是能够访问父类方法,就一定能访问子类的相同方法;如果原来不需要catch,现在也不需要
public void m() throws AException
{};
}public class B extends A{
public void m() throws AException, BException
{};
}public class Test {
public static void main(Sting[] args) {
A obj = new B();
try {
obj.m(); //父类引用,m方法只抛出了AException,但实际调用的是B类的m方法,会抛出BException,但这里就捕获不到了
} catch (AException) {
}
}
}
A obj = new B();这一句含义到底该怎么理解它呢?