ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class A {
final String tag() { return "A"; }
}
class B extends A {
String tag(int x) { return "B" + x; }
}
// in main:
A a = new B();
System.out.println(a.tag());- A. A
- B. B
- C. Compilation error: tag() cannot be hidden
- D. Compilation error: B must override tag()
Correct answer: A. A
A.tag() is final, so B cannot override it (B.tag(int) is a different overload, not an override attempt, since it has a parameter). a.tag() always resolves to A's own final implementation, printing "A".
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "1"; } }; struct D2…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "X"; } }; struct D2…
- What happens when this is compiled? java interface A { default void m() { System.out.println("A"); } } interface B { default void m() {…
- What happens when Base b; is added inside main, right before the existing lines? cpp struct Base { virtual void f() = 0; }; struct Derived…
- What happens when this is compiled? cpp struct A { int x; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; d.x =…
- What is printed? cpp struct Base { virtual ~Base() {} }; struct Derived : Base {}; struct Other : Base {}; int main() { Base b = new…