ProgrammingModerateAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
class P { String f = "P"; static String s() { return "P"; } String i() { return "P"; } }
class C extends P { String f = "C"; static String s() { return "C"; } String i() { return "C"; } }
// in main:
P p = new C();
System.out.print(p.s() + p.i() + p.f);- A. CCC
- B. PCP
- C. PCC
- D. CCP
Correct answer: B. PCP
Only instance methods are overridden. Static methods are hidden and chosen by the static type P, and fields are also resolved by the static type, so s() and f give P while i() dispatches to C.
More OOP with C++ and Java questions
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("L"); } static void f(Integer x) {…
- What is printed? java String x = "a"; final String y = "a"; System.out.print(("ab" == x + "b") + " "); System.out.print(("ab" == y + "b")…
- What is printed? java // static methods of the main class: static int f() { int x = 1; try { return x; } finally { x = 5; } } static…
- What is printed? java class A { static int x = f(); static int y = 10; static int f() { return y 2; } } // in main: System.out.print(A.x +…
- What is printed? java class P { P() { show(); } void show() { System.out.print("P"); } } class C extends P { int v = 7; String s = "x"…
- Which statement about this code is correct? java try { new java.io.FileReader("a.txt").close(); } catch (java.io.IOException | Exception…