ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class P {
int x = 10;
int getX() { return x; }
}
class C extends P {
int x = 20;
int getX() { return x; }
}
// in main:
P p = new C();
System.out.print(p.x + " " + p.getX());- A. 20 20
- B. 10 20
- C. 10 10
- D. 20 10
Correct answer: B. 10 20
Fields are not polymorphic: p.x uses the declared type P and reads P's x, 10. The method call is dynamically dispatched to C.getX, which reads C's x, 20.
More OOP with C++ and Java questions
- What is printed (default JVM settings)? java Integer x = 127, y = 127; Integer p = 128, q = 128; System.out.print((x == y) + " " + (p ==…
- What is printed? java // static methods of the main class: static void f(Object o) { System.out.print("Object"); } static void f(String s)…
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("long"); } static void f(Integer x) {…
- What is printed? java class P { P() { show(); } void show() { System.out.print("P "); } } class C extends P { int x = 10; void show() {…
- What is printed? java class T { static { System.out.print("S"); } { System.out.print("I"); } T() { System.out.print("C"); } } // in main…
- What is printed? java // static methods of the main class: static int f() { int x = 1; try { return x; } finally { x = 5; } } static int…