ProgrammingVery hardWipro · Cognizant technical pattern
What is printed?
What is printed?
class A {
void m(A a) { System.out.print("AA"); }
}
class B extends A {
void m(A a) { System.out.print("BA"); }
void m(B b) { System.out.print("BB"); }
}
// in main:
A x = new B();
B y = new B();
x.m(y);- A. BB
- B. AA
- C. Compilation error: ambiguous call
- D. BA
Correct answer: D. BA
Overload choice happens at compile time using the static type of x (A), which has only m(A), so the signature m(A) is chosen. At run time the object is a B, which overrides m(A), so BA prints. m(B) is a separate overload that A’s type never sees.
More OOP with C++ and Java questions
- Class P is in package a and declares protected int x. Class C is in package b and extends P. Inside an instance method of C, which of…
- What happens when this Java class is compiled? java class Util { static void f(List<String> l) { } static void f(List<Integer> l) { } }
- How many of the following statements about equals() and hashCode() in Java are correct? (i) If a.equals(b) is true, a.hashCode() must…
- On a typical 64-bit compiler (8-byte pointers, 4-byte int, natural alignment), what does sizeof(P) print? cpp class P { int id; public…
- What is printed? java class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } } class C…
- What is printed? java class P { P() { show(); } void show() { } } class C extends P { final int a = 5; int b = 7; final String s = "s"…