ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement
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);
y.m(x);
y.m(y);- A. BBBABB
- B. BABABB
- C. AABABB
- D. BBBBBB
Correct answer: B. BABABB
The overload is chosen at compile time from static types: x is an A, which only has m(A), so x.m(y) means m(A), overridden in B: BA. y.m(x) passes an A: BA. y.m(y) picks the more specific m(B): BB.
More OOP with C++ and Java questions
- Which lines fail to compile? java List<Integer> ints = new ArrayList<>(); List<Number> a = ints; // line 1 List<? extends Number> b =…
- What happens? java boolean flag = true; Integer none = null; Integer r1 = flag ? null : 0; System.out.print(r1); Integer r2 = flag ? none…
- What is printed? java System.out.print(Math.abs(Integer.MINVALUE) + " "); System.out.print(Integer.MAXVALUE + 1 == Integer.MINVALUE);
- What is printed? java System.out.print((-7 / 2 == -3) + " " + (-7 % 2 == 1) + " " + (Math.floorMod(-7, 2) == 1) + " " + (7 % -2 == 1));
- Which line fails to compile? java byte b = 10; b += 5; // line 1 b++; // line 2 b = b + 1; // line 3 b = 10 + 20; // line 4
- What is printed? java int i = 0, j = 0; boolean p = (i++ > 0) & (i++ > 0); boolean q = (j++ > 0) && (j++ > 0); System.out.print(i + " " +…