在 S G Ganesh 和 Tushar Sharma 所著的“Oracle Certified Professional Java SE 7 Programmer Exams 1Z0-804 and 1Z0-805 A Comprehensive OCPJP 7 Certification Guide”一书中,声明
"if a method is declared in 2 or more interfaces, and if that method declares to throw different exceptions in the throws clause, the implementation should list all these exceptions" (page 347)
好吧,那我试过了
public interface I1 {
public void x() throws I1Exception;
}
public interface I2 {
public void x() throws I2Exception;
}
public class I1Exception extends Exception {
}
public class I2Exception extends Exception {
}
public class Sample implements I1, I2{
@Override
public void x() throws I2Exception {
throw new I2Exception();
}
@Override
public void x() throws I1Exception {
throw new I1Exception();
}
}
当然,异常不是方法签名的一部分,所以编译器会提示第二个方法是重复的。
另一方面
@Override
public void x() throws I1Exception, I2Exception {
throw new I1Exception();
}
与两个接口(interface)都不兼容,因为它声明的检查异常比每个接口(interface)的任何一种方法都多,单独使用。
这意味着我不明白这本书说的是什么还是这意味着这本书的说法不准确?
最佳答案
再想一想,我认为这本书的意图是说你必须同时满足这两个接口(interface)。
因此该方法应该抛出(粗略地说)两种方法的异常集的交集。如果这些集合不相交,则该方法不能抛出任何东西。所以这个:
@Override
public void x() {
}
两个接口(interface)都可以。
(因为继承有点复杂,但是你明白了。)
从我的角度来看
"if a method is declared in 2 or more interfaces, and if that method declares to throw different exceptions in the throws clause, the implementation should list all these exceptions" (page 347)
不可能是正确的,因为它在实践中不起作用。您(在大多数情况下)无法在实现中列出所有这些异常。有一些异常,例如未经检查的异常或相同/兼容的异常集。
但是我在 JLS 中找不到这方面的规范引用。
关于java - 类实现了两个接口(interface),方法相同,检查异常不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26300828/