ProgrammingHardGATE CS · TCS NQT Prime · Product Company SDE

java class Base { int v = 1; } class Derived extends Base { int v = 2; } // main: Base b = new Derived(); System.out.print(b.v); What is printed?

class Base { int v = 1; }
class Derived extends Base { int v = 2; }
// main:
Base b = new Derived();
System.out.print(b.v);
What is printed?
  1. A. 2
  2. B. 1
  3. C. 0
  4. D. Compile error

Correct answer: B. 1

Fields are not polymorphic in Java either; b.v is resolved using b's declared type Base, so it reads Base's v, which is 1, even though the object is really a Derived.

More OOP with C++ and Java questions

Exams that ask this topic