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());
  1. A. 20 20
  2. B. 10 20
  3. C. 10 10
  4. 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

Exams that ask this topic