ProgrammingHardProduct-company MCQ pattern
Does this compile?
Does this compile?
class A { void m() throws java.io.IOException {} }
class B extends A {
@Override
void m() throws java.io.FileNotFoundException {}
}- A. No: an overriding method must declare the exact same throws clause as the superclass method
- B. Yes: FileNotFoundException is a subtype of IOException, so narrowing the throws clause is allowed
- C. No: overriding methods cannot declare any checked exception
- D. Yes, but only if B.m() is also declared final
Correct answer: B. Yes: FileNotFoundException is a subtype of IOException, so narrowing the throws clause is allowed
An overriding method may declare a checked exception that is the same as, or a subtype of, the one declared in the overridden method (or declare none at all). FileNotFoundException extends IOException, so this narrowing is legal.
More OOP with C++ and Java questions
- What is printed, and what happens to the RuntimeException? java static int f() { try { throw new RuntimeException("x"); } finally { return…
- What is printed? java class MyEx extends RuntimeException { public String getMessage() { return "custom:" + super.getMessage(); } } public…
- Does this compile? java interface I { void m() throws java.io.IOException; } class C implements I { public void m() throws…
- 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) + " " +…