About Question enthuware.ocpjp.v7.2.1346:
Posted: Thu Oct 17, 2013 8:23 am
I'm having trouble understanding this. If a class says it implements these two interfaces, the correct way of doing it is as follows:
Why is this invalid?
My thoughts are as follows:
A class implementing these two interfaces, if it throws any exceptions, must satisfy both exceptions thrown in the interfaces. It would make more sense to me if it was valid to throw an IOException, since FileNotFoundException IS-A IOException, but IOException is not necessarily a FileNotFoundException (upcast, downcast). So declaring "throws IOException" would satisfy both interfaces. However throwing FileNotFoundException does not always satisfy I1, since the IOException could, for example, be a EOFException. With the above implementation it is not possible to have an implementation that throws EOFException, although interface I1 would allow it. I know I'm missing a point, I just can't see it
Code: Select all
interface I1 {
void m1() throws IOException;
}
interface I2 {
void m1() throws FileNotFoundException;
}
class IDontGetIt implements I1, I2 {
@Override
public void m1() throws FileNotFoundException {
}
}
Code: Select all
class ThisIsHowIThinkItShouldBe implements I1, I2 {
@Override
public void m1() throws IOException {
}
}
A class implementing these two interfaces, if it throws any exceptions, must satisfy both exceptions thrown in the interfaces. It would make more sense to me if it was valid to throw an IOException, since FileNotFoundException IS-A IOException, but IOException is not necessarily a FileNotFoundException (upcast, downcast). So declaring "throws IOException" would satisfy both interfaces. However throwing FileNotFoundException does not always satisfy I1, since the IOException could, for example, be a EOFException. With the above implementation it is not possible to have an implementation that throws EOFException, although interface I1 would allow it. I know I'm missing a point, I just can't see it