ProgrammingVery hardWipro · Cognizant pattern

What is printed?

What is printed?
class A {
    void greet() { System.out.print("A-inst "); }
    static void greet(int x) { System.out.print("A-static "); }
}
class B extends A {
    @Override
    void greet() { System.out.print("B-inst "); }
}
// in main:
A obj = new B();
obj.greet();
obj.greet(1);
B b2 = new B();
b2.greet(2);
  1. A. A-inst A-static B-static
  2. B. B-inst A-static A-static
  3. C. B-inst B-static A-static
  4. D. B-inst A-static B-static

Correct answer: B. B-inst A-static A-static

greet() with no args is overridden (dynamic dispatch) so obj.greet() runs B's version: B-inst. greet(int) is static and not overridden; both obj.greet(1) and b2.greet(2) resolve to A.greet(int) at compile time regardless of declared type B or A, printing A-static both times.

More OOP with C++ and Java questions

Exams that ask this topic