Consider the following Java classes:
These classes compile, even though foo()
in B
throws a different exception from foo()
in A
. Explain why
the classes compile despite this difference.
Suppose we removed @Override
from foo()
in B
, added
import java.io.IOException;
to the top of class B
and changed the declaration of foo()
in B
to:
void foo() throws IOException {
throw new IOException();
}
Would the classes still compile? What does your answer tell you about the role of exceptions in method overloading in Java?
Finally, with the original set of classes, suppose we added this demo class:
public class Demo {
public static void main(String[] args) {
A myB = new B();
try {
myB.foo();
} catch (MyExceptionD e) {
System.out.println("Exception of type MyExceptionD was thrown.");
}
}
}
Explain why this class will fail to compile. Explain what simple change you can make to Demo
to solve the problem.