ProgrammingHardTCS NQT · Infosys pattern
Does this compile?
Does this compile?
class Base {
void greet() { System.out.println("Base.greet"); }
}
class Derived extends Base {
@Override
void greet() throws java.io.IOException {
System.out.println("Derived.greet");
throw new java.io.IOException();
}
}- A. Yes, it compiles fine
- B. No: an override cannot declare a new checked exception not present on the overridden method
- C. Yes, but only if Base also declares throws IOException elsewhere
- D. No: @Override cannot be combined with a throws clause
Correct answer: B. No: an override cannot declare a new checked exception not present on the overridden method
Base.greet() declares no checked exceptions at all, so Derived's override is forbidden from adding `throws IOException` (a checked exception), since that would let callers who only know about Base's contract be surprised by an unhandled checked exception — this is a compile-time error.
More OOP with C++ and Java questions
- What is printed? java class Repo<T> { private List<T> items = new ArrayList<>(); void add(T item) { items.add(item); } T get(int i) {…
- What is printed? java interface Shape { double area(); default String describe() { return "Shape with area " + area(); } } class Square…
- What is printed? cpp struct A { int x = 10; virtual int getX() { return x; } }; struct B : A { int x = 20; int getX() override { return x…
- What is printed? java class Util { static int counter = 0; static void inc() { counter++; } } class UtilChild extends Util { } public…
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? java interface Shape { static double unit() { return 1.0; } double area(); } class Square implements Shape { double side…