ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class A {
static void m() { System.out.println("A.static"); }
}
class B extends A {
static void m() { System.out.println("B.static"); }
}
// in main:
A a = new B();
a.m();- A. B.static
- B. A.static
- C. Compile-time error: static methods cannot be hidden
- D. It prints both
Correct answer: B. A.static
Static methods are not polymorphic; they are hidden, not overridden, and resolved using the compile-time (static) type of the reference. a is declared as type A, so a.m() calls A.m() regardless of the runtime type of the object.
More OOP with C++ and Java questions
- What happens when this is compiled? cpp struct A { virtual void f() final { cout << "A"; } }; struct B : A { void f() override { cout <<…
- What happens when this is compiled? java class A { int m() { return 1; } double m() { return 1.0; } }
- What is printed? cpp void f(int p) { cout << "nonconst "; } void f(const int p) { cout << "const "; } int main() { int x = 5; int p = &x…
- Does this compile? java class Outer { private int x = 5; class Inner { void show() { System.out.println(x); } } }
- What is printed? cpp struct Base { virtual void f() { cout << "Base"; } }; struct Derived : Base { void f() { cout << "Derived"; } }; int…
- What is printed? java class Picker { static void f(int a, int b) { System.out.print("fixed"); } static void f(int... a) {…