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);- A. A-inst A-static B-static
- B. B-inst A-static A-static
- C. B-inst B-static A-static
- 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
- What is printed? cpp class Base { public: void info() { cout << "Base::info "; helper(); } void helper() { cout << "Base::helper"; } }…
- What is printed? cpp struct A { int v = 1; virtual void show() { cout << v; } }; struct B : A { int v = 2; void show() override { cout <<…
- What is printed? cpp struct Base { virtual void f() { cout << "Base-f "; g(); } void g() { cout << "Base-g"; } }; struct Derived : Base {…
- What is printed? java class A { static { System.out.print("A-static "); } } class B extends A { static { System.out.print("B-static "); }…
- What is printed? java class Parent { int bonus() { return 10; } } class Child extends Parent { static int bonus(int n) { return n + 1; } }…
- What is printed? java class A { { System.out.print("IB-A "); } A() { System.out.print("CTOR-A "); } } class B extends A { {…