ProgrammingHardIBM · Deloitte pattern
Does this compile?
Does this compile?
interface I { void m() throws java.io.IOException; }
class C implements I {
public void m() throws InterruptedException {}
}- A. Yes, any checked exception may be substituted when implementing an interface method
- B. No: InterruptedException is not a subtype of IOException, so the implementing method's throws clause is incompatible
- C. Yes, because interface methods never constrain throws clauses
- D. No, because implementing classes cannot declare checked exceptions at all
Correct answer: B. No: InterruptedException is not a subtype of IOException, so the implementing method's throws clause is incompatible
An implementing (or overriding) method's checked exceptions must be the declared type or a subtype of it. InterruptedException and IOException are unrelated checked exceptions, so C.m() violates the interface contract and fails to compile.
More OOP with C++ and Java questions
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java // in main: String a = "hello"; String b = "hello"; String c = new String("hello"); String d = c.intern()…
- What is printed? java // in main: Integer a = 100; Integer b = 100; Integer c = 200; Integer d = 200; System.out.println((a == b) + " " +…
- What is printed? java // in main: String s1 = "Java"; String s2 = new StringBuilder("Java").toString(); System.out.println((s1 == s2) + "…
- What is printed? java // in main: String s = "hello"; s.concat(" world"); System.out.println(s); String t = s.concat(" world")…
- What is printed? java class Node { int val; Node(int v) { val = v; } @Override public int hashCode() { return 42; } @Override public…