ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Base {
void process() {
System.out.print("Base.process ");
validate();
}
protected void validate() { System.out.print("Base.validate "); }
}
class Sub extends Base {
@Override
protected void validate() {
System.out.print("Sub.validate ");
throw new IllegalStateException("bad");
}
}
public class Main {
public static void main(String[] args) {
try {
new Sub().process();
} catch (IllegalStateException e) {
System.out.print("caught:" + e.getMessage());
}
}
}- A. Base.process Base.validate
- B. Base.process Sub.validate caught:bad
- C. Compile-time error: validate() cannot throw since Base's version doesn't declare it
- D. Sub.validate Base.process caught:bad
Correct answer: B. Base.process Sub.validate caught:bad
process() is inherited unchanged and calls validate() polymorphically; since the real object is a Sub, it dispatches to Sub's override, printing Sub.validate, which then throws. IllegalStateException is unchecked, so overriding with a throw needs no throws declaration; it propagates up and is caught in main, printing caught:bad.
More OOP with C++ and Java questions
- What is printed? java class Base { public String toString() { return "Base[" + describe() + "]"; } protected String describe() { return…
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B { B() { cout << "B"; } }; struct C : A, B { C() { cout << "C"; } }; int…
- What is printed? cpp struct Animal { virtual std::string sound() const { return "..."; } }; struct Dog : Animal { std::string sound()…
- What is printed? cpp struct Shape { virtual double area() const = 0; void report() const { std::cout << "Area: " << area(); } }; struct…
- What is the behavior? cpp struct Base { ~Base() { std::cout << "~Base "; } // NOT virtual }; struct Derived : Base { int data = new…
- What is printed? cpp struct A { virtual void f(int x) { std::cout << "A::f(int) " << x; } }; struct B : A { virtual void f(double x) {…