ProgrammingHardWipro NLTH · GATE CS

What is printed?

What is printed?
class A { int x = 1; }
class B extends A { int x = 2; }
// in main:
A a = new B();
System.out.print(a.x + " " + ((B) a).x);
  1. A. 1 2
  2. B. 2 2
  3. C. 1 1
  4. D. 2 1

Correct answer: A. 1 2

Fields are not polymorphic: a.x uses the declared type A (1), while the cast to B selects B's own field (2).

More OOP with C++ and Java questions

Exams that ask this topic